Results 1 to 4 of 4

Thread: Passing Variables to Include Files

  1. #1
    learning_brain's Avatar
    learning_brain is offline x10 Sophmore
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    207

    Passing Variables to Include Files

    This is a little more complex than the title suggests.

    I have a menu system in a header - which is, as you might expect, an include file.

    http://www.donbur.co.uk/eng/css/csstest.php

    Within the menu, I have options for making the <dd> elements with a "current" class or not...

    So... my first step was to get the current url.

    PHP Code:
                //obtain full current url
                
    $protocol $_SERVER['HTTPS'] == 'on' 'https' 'http';
                
    $host $_SERVER['HTTP_HOST'];
                
    $url $_SERVER['REQUEST_URI'];
                
    $currentFullURL $protocol.'://'.$host.$url
    All pretty basic stuff - provided it resides in the original file - not the include file (which would have been more convenient). Testing fro the main file, this works a treat.

    Then a simple line in the include...

    PHP Code:

    <dd <?php if($currentFullURL == "http://www.donbur.co.uk/eng/about/history.php"){?>class="current"<?php ?>>
    Theoretically, this would then pick up that its the same page and change the class to "current". The css takes care of the rest.

    NOPE...

    For some unknown and frustrating reason, the $currentFullURL variable in the main file is not passing to the include. If I try to echo this variable from the include (anywhere in the include), it's an empty variable..... why??????

    I have looked at putting it into a Session variable and also a $GLOBALS variable - all without success.

    Am I missing something???

    Rich


    Twitter: #wishingwebs

  2. #2
    descalzo's Avatar
    descalzo is offline Grim Squeaker
    Join Date
    Jul 2009
    Location
    Ankh-Morpork
    Posts
    8,279

    Re: Passing Variables to Include Files

    Don't read the book before it is printed.
    Nothing is always absolutely so.

  3. #3
    learning_brain's Avatar
    learning_brain is offline x10 Sophmore
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    207

    Re: Passing Variables to Include Files

    Quote Originally Posted by descalzo View Post
    Don't read the book before it is printed.
    Nice cryptic response to get me started in the morning!!

    I've had a good think about this and managed to come up with a working solution.

    As the url has to be "GOT" in the main file, I have passed this variable in the include address and then used the GET method in the include itself - which works.

    ie.

    Main Page
    PHP Code:
    get the full url and assign to variable $currentURL

    include('./menu.php?currentURL='.$currerntURL.''); 
    Include
    PHP Code:
    if($_GET['currentURL']=="whatever the link is"){
    class=
    "current"

    Phew!


    Twitter: #wishingwebs

  4. #4
    misson is offline x10 Spammer
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,573

    Re: Passing Variables to Include Files

    For essentially the same reasons that globals are bad, code should be isolated into local scopes (basically, functions); this is part of separating concerns. Instead of having code output the menu at a global level, create a view: a function or class that outputs it. You can either call the function/instantiate the class in the main controller script, or in some other menu controller script included in the main script. That way, you can pass any custom classes to the appropriate function/set the appropriate property instead of mucking about with global variables or superglobals. Also, you won't need a test for every element when outputting the element's classes.

    You'll need to decide on a standard way of creating identifiers for each type of object you need to deal with (e.g. pages, links and menu items), and a way of mapping the identifier to each object given the type. URLs are identifiers, so you could use the path (e.g. "/eng/about/history") or part of the path (e.g. "about/history") as an identifier. The downside to this is that URL paths include characters that aren't legal in HTML identifiers. You could use a unique page name (e.g. "history") that would be a valid HTML ID and include a mapping from the ID to URLs.

    For example, an outline off using a function; views/sitemenu.php:
    PHP Code:
    <?php
    function displaySiteMenu($current) {
        static 
    $items = array(
            ...
            );
        
        
    $items[$current]['class'] .= ' current';

        foreach (
    $items as $id => $item) {
            ...
        }
    }
    fragments/sitemenu.php:
    PHP Code:
    <?php
    include_once('views/sitemenu.php');
    displaySiteMenu(url2id($_SERVER['REQUEST_URI']));
    If you don't want to construct the menu programmatically, you can instead define the menu in an HTML fragment file (or a document in some other data structuring language), load it with an HTML (or whatever) parser, modify it as necessary & output. This approach is particularly useful if there are designers who know HTML but not PHP working on a project (which I'm guessing isn't currently true of your project). There isn't much of a performance impact over the original approach. Of course, at this point you may as well pick an existing MVC framework to use rather than implementing one yourself (unless the point is self-education).
    PHP Code:
    abstract class View {
        abstract function 
    __toString();
        
    /* output this view */
        
    function display() {
            echo (string)
    $this;
        }
        
    /* prepare for output */
        
    abstract function generate();
    }

    /* produces HTML. If you have views that create HTML programmatically, 
     * refactor some of HTMLView into  an HTMLTemplate class that loads the 
     * HTML fragment.
     * You could also add methods to HTMLView that allows hierarchical views, 
     * where one view can be a child of another.
     * Example implementation based on DOMDocument.
     */
    abstract class HTMLView extends View {
        protected 
    $_doc# HTML parser, e.g. DOMDocument
            
    $_path# document traverser, e.g. DOMXPath
            
    $_file# HTML fragment

        
    function __construct($file) {
            
    parent::__construct();
            
    $this->_file $file;
            
    $this->generate();
        }
        function 
    __toString() {
            
    /* Pass root node to prevent DOCTYPE declaration, <html> and 
             * <body> from being included in result. Requires PHP >= 5.3.6
             */
            
    return $this->_doc->saveHTML($this->_doc->documentElement);
        }
        function 
    generate() {
            if (! 
    $this->_doc) {
                
    $this->_doc = new DOMDocument;
                
    $this->doc->validateOnParse TRUE# so getElementById will work
                
    $this->_load();
                
    $this->_revise();
            }
        }
        
    /* load HTML fragment */
        
    protected function _load() {
            
    $this->_doc->loadHTMLFile($this->_file);
            
    $this->_path = new DOMXPath($this->_doc);
        
    # so you can use php functions in XPath expressions
        
    $this->path->registerNamespace("php""http://php.net/xpath");
        
    $this->path->registerPhpFunctions();
        }
        
    /* modify loaded HTML */
        
    abstract protected function _revise();
    }

    class 
    HTMLMenuView extends HTMLView {
        public 
    $current;

        protected function 
    _revise() {
            
    $this->_markCurrentItem();
            ...
        }

        protected function 
    _markCurrentItem() {
            
    # "/path/to/" could simply be "//" to search all <dd>
            
    $dds $this->_path->query("/path/to/dd[@id='{$this->current}_menu_item']");
            if (
    $dds->length) {
                
    # assume node is an element
                
    $classes $dds->item(0)->getAttribute('class');
                
    $dds->item(0)->setAttribute('class'$classes ' current');
            }
        }

    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Jon Skeet's and Eric Raymond's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

Similar Threads

  1. php Include files
    By respond in forum Free Hosting
    Replies: 1
    Last Post: 11-11-2009, 11:34 AM
  2. Using Include Files with html on X10Hosting
    By frankfriend in forum Tutorials
    Replies: 0
    Last Post: 07-06-2009, 01:38 PM
  3. Passing JS variables from one function to another
    By Tenant in forum Scripts, 3rd Party Apps, and Programming
    Replies: 4
    Last Post: 02-24-2009, 12:43 PM
  4. How do I put include files in html - what is the syntax please
    By frankfriend in forum Scripts, 3rd Party Apps, and Programming
    Replies: 4
    Last Post: 02-17-2009, 02:19 PM
  5. Passing variables from page to page
    By os242 in forum Scripts, 3rd Party Apps, and Programming
    Replies: 3
    Last Post: 09-15-2007, 02:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
dedicated servers