note 67930 deleted from language.oop5.autoload by crell
| From: | crell@php.net | Date: | Mon, 04 Apr 2022 16:11:04 +0000 |
| Subject: | note 67930 deleted from language.oop5.autoload by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218029@lists.php.net to get a copy of this message | ||
Note Submitter: alexey at renatasystems dot org
----
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().