note 34604 added to function.require
| From: | Peter at rack1 dot php dot net | Date: | Thu, 31 Jul 2003 21:52:06 +0000 |
| Subject: | note 34604 added to function.require | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-53113@lists.php.net to get a copy of this message | ||
Further to the comments on functions/classes in include files, php include is not a simple file
include; it also evaluates the included code, which in the case of classes/functions seems to put
them in some sort of global context, _not_ in the scope of the function in which they are included.
Put a simple class in a file, say test2.class.php:
<?php
class newobj
{
function newobj()
{
print 'hello';
}
}
?>
Now include that in another file, say test.class.php:
<?php
class obj
{
function obj()
{
print 'hello? ';
include 'test2.class.php';
}
}
?>
Now execute that with:
include 'test.class.php';
$obj = new obj();
$newobj = new newobj();
Prints 'hello? hello'
Now take the code from test2.class.php and put it in test.class.php
<?php
class obj
{
function obj()
{
print 'hello? ';
class newobj
{
function newobj()
{
print 'hello';
}
}
}
}
?>
execute it again, and you get a fatal error: Class declarations may not be nested
However, eval the inner class:
<?php
class obj
{
function obj()
{
print 'hello? ';
eval("class newobj
{
function newobj()
{
print 'hello';
}
}");
}
}
?>
execute, and, hey presto, it works: 'hello? hello'
Strange, but true
----
Manual Page -- http://www.php.net/manual/en/function.require.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34604
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34604&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34604&report=yes