note 73264 deleted from language.oop5 by danbrown
| From: | danbrown@php.net | Date: | Wed, 17 Jun 2009 18:49:54 +0000 |
| Subject: | note 73264 deleted from language.oop5 by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157019@lists.php.net to get a copy of this message | ||
Note Submitter: mail at touchmypixel dot com
----
An addition to the earlier post on creating anonymous objects.
You can make a quick anonmymous object just by using an unset variable as an object.
$foo->bar = "Hello World";
var_dump($foo->bar);
If you want to set it you can just use NULL or an empty string.
$foo = NULL;
$foo->bar = "Hello World";
var_dump($foo->bar);
This is extremely useful if you need to set a variable before using it, for example as a STATIC in a
CLASS.
class MyClass {
static $foo = NULL;
}
//
MyClass::$foo->bar = "Hello World";
You can also just create a NULL object and cast it as OBJECT.
$foo = (object) NULL;
This cannot be used when creating CLASS STATICs though.
You can get some nice functionality out of this by combining some of the earlier examples into a
simple function (thanks guys).
function object(){
$o = (object) NULL;
$n = func_num_args( ) ;
for ( $i = 0 ; $i < $n ; $i += 2 ) {
$o->{func_get_arg($i)} = func_get_arg($i + 1) ;
}
return($o);
}
This lets you create an anonymous object, with variables already set, which is useful for single
line creation, for example sending an object through to a function.
function say($obj){
var_dump($obj->message);
}
say(object("message", "Hello World"));
Hope this helps for anyone looking how to create anonymous objects in PHP (anyone from the
ECMAScript world - JavaScript or ActionScript!)