The PHP Online Conference 2021

Voting

Please answer this simple SPAM challenge: min(five, nine)?
(Example: nine)

The Note You're Voting On

alexey at renatasystems dot org
14 years ago
While using an "autoloading" method you should pay attention to variables scope. Because of new file will be included INSIDE of magic function __autoload - all of declared in such file global scope variables will be only available within this function and nowhere else. This will cause strange behaviour in some cases. For example:

file bar.class.php:

<?php

$somedata
= 'Some data';     /* global scope in common way */

class bar {

    function
__construct()   
    {   
        global
$somedata;    /* reference to global scope variable */
       
       
if ( isset($somedata) )
        {
           
var_dump($somedata);
        }
        else
        {
            die(
'No data!');
        }
    }
}
?>

Attempt to load this file in common way:

<?php

require 'bar.class.php';

$foo = new bar();

?>

this will output (as expected):

string(9) "Some data"

But in case of __autoload:

<?php

function __autoload($classname)
{
    require
$classname . '.class.php';
}

$foo = new bar();

?>

you could expect that this script will return the same but no, it will return "No data!", because defenition of $somedata after requiring treats as local within user-defined function __autoload().

<< Back to user notes page

To Top