note 73264 added to language.oop5

From: Date: Thu, 15 Feb 2007 05:05:44 +0000
Subject: note 73264 added to language.oop5
Groups: php.notes 
Request: Send a blank email to php-notes+get-123400@lists.php.net to get a copy of this message
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!) ---- Server IP: 203.220.0.234 Probable Submitter: 220.238.9.24 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.php Edit -- https://master.php.net/note/edit/73264 Del: integrated -- https://master.php.net/note/delete/73264/integrated Del: useless -- https://master.php.net/note/delete/73264/useless Del: bad code -- https://master.php.net/note/delete/73264/bad+code Del: spam -- https://master.php.net/note/delete/73264/spam Del: non-english -- https://master.php.net/note/delete/73264/non-english Del: in docs -- https://master.php.net/note/delete/73264/in+docs Del: other reasons-- https://master.php.net/note/delete/73264 Reject -- https://master.php.net/note/reject/73264 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#123400) next »