views:

29

answers:

1

Can somebody explain to me why PHP does not report a warning or error when accessing a property of a empty object (var is not assigned)?

For example:

$oMyObject->test = 'hello world'; // $oMyObject is not assigned but no warning or error

When i do this, it produces an error:

$oMyObject->test(); // Error: Calling function on non-object

Version info:

Windows XP
XAMPP Windows Version 1.7.0
Apache/2.2.11 (Win32) 
PHP 5.2.8
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Xdebug v2.0.4, Copyright (c) 2002-2008, by Derick Rethans

Why? Tried to set error_reporting( E_ALL ) but still no error or warning.

A: 

$oMyObject->text = 'hello world'; is a completely valid statement, provided text is declared public and not private or protected. As for $oMyObject->text(), you need to provide some more information. What kind of error you get? Is the function text() public or private or protected? Can you post what the function does?

Azeem Michael
I know that it is a valid statement but that is not the case. $oMyObject->test() is just an example. PHP reports an error about the empty var, it is a non-object. That is OK. t is not important what the function do because there is no run-time information because the var is empty. It has nothing to do with public, private etc. It is about that the var is empty, that it is not assigned! In the first case ($oMyObject->test = 'Hello World') i don't see any warning or error. That's weird.
Erwinus
sorry, didn't get you the first time. It seems php allows dynamic instance properties.
Azeem Michael
But is it a bug or what is it? Anyone?
Erwinus
Actually some languages like JavaScript and Python do allow you to dynamically create anonymous objects/functions without defining the class. It seems PHP also allows this.You can also create you test() function by doing this. $obj->test = function(){ echo 'This is a test';}; $test = $obj->test; $test;
Azeem Michael
I understand but.... the var $oMyObject is empty/not assigned! So why i don't see any error? In javascript you get an error when you try to access it when it is undefined. Try it in javascript and you will see. Why is php only reporting errors when you want to call a function?
Erwinus
when you say $obj->test = 'hello world' or $obj = (object)'hello world' (same thing) php invokes it's generic stdClass (http://www.php.net/manual/en/language.types.object.php#language.types.object.casting) to dynamically create the object. It's like saying $obj = stdClass; $obj->test = 'hello world';
Azeem Michael