I ran across this today and it surprised me:
$ php -r 'define("X", "stdClass"); $x = new X; var_dump($x);';
Fatal error: Cannot instantiate non-existent class: x in Command line
code on line 1
I tested on php 4.4.0, 4.3.8 and 5.0.3, with the result that all
versions exhibit the same behavior.
Clearly there is an easy work around:
$ php -r 'define("X", "stdClass"); $y = X; $x = new $y; var_dump($x);'
object(stdClass)(0) {
}
But I was wondering if anyone could enlighten me as to why php would
be upset interpreting the constant as the class name. Thanks.
Regards,
Jason
http://blog.casey-sweat.us/
But I was wondering if anyone could enlighten me as to why php would
be upset interpreting the constant as the class name. Thanks.
class Foo {
function get_name() { return 'Foo'; }
}
class Bar {
function get_name() { return 'Bar'; }
}
define('Foo', 'Bar');
$C = new Foo();
echo $C->get_name();
// output: Foo
// you might have been expecting: Bar
This "issue" also affects static method calls:
Foo::get_name();
// returns: Foo
// even though Foo (the constant) resolves to: Bar
HTH.
S
can u tell me why
php -r 'function myfunc(){} define("X", "myfunc"); X(); '
Fatal error: Call to undefined function: x() in Command line code on line 1
but not calling myfunc?
wrong list. :)
wrong list. :)
My question was not "how do I work around this?". I included that in
my original post. My question was "why is it like this?" which I
thought was more germane to the internals list.
An unquoted string would have to first be thought of as the class
name, but if that does not exist, php is not then checking to see if
it is actually a defined constant.
My questions was basically is this a performance issue or just an
undesired behavior for some other reason?
Regards,
Jason
http://blog.casey-sweat.us/
Hello Jason,
new doesn't expect a string which a constant in fact is. It expects a
class name. Thus the class name cannot be constified. You'd need to use
reflection for that:
$r = new ReflectionClass($name); $o = $r->newInstance();
best regards
marcus
Monday, September 19, 2005, 6:58:31 PM, you wrote:
wrong list. :)
My question was not "how do I work around this?". I included that in
my original post. My question was "why is it like this?" which I
thought was more germane to the internals list.
An unquoted string would have to first be thought of as the class
name, but if that does not exist, php is not then checking to see if
it is actually a defined constant.
My questions was basically is this a performance issue or just an
undesired behavior for some other reason?Regards,
Jason
http://blog.casey-sweat.us/
--
Best regards,
Marcus