note 51627 added to language.oop5.static

From: Date: Tue, 05 Apr 2005 22:40:44 +0000
Subject: note 51627 added to language.oop5.static
Groups: php.notes 
Request: Send a blank email to php-notes+get-87546@lists.php.net to get a copy of this message
I had trouble getting a static member to be an instance of a class. Here's a code example that DOESN'T work. <?php // This doesn't work. class XYZ { // The following line will throw a syntax error. public static $ABC = new ABC(); } class ABC { } $myXyz = new XYZ(); var_dump($myXyz); var_dump(XYZ::$ABC); ?> I get the following entry in my error log. [05-Apr-2005 18:27:41] PHP Parse error: syntax error, unexpected T_NEW in staticTest.php on line 7 Since PHP doesn't appear to allow static constructor methods, I was only able to resolve this problem by moving the initialization outside of the class. To make my code more self-documenting I put it above the class. The revised example below appears to work. <?php // This will work. // Moved the static variable's initialization logic outside the class. XYZ::$ABC = new ABC(); class XYZ { // I'm just declaring the static variable here, but I'm not initializing it. public static $ABC; } class ABC { } $myXyz = new XYZ(); var_dump($myXyz); var_dump(XYZ::$ABC); ?> ---- Manual Page -- http://www.php.net/manual/en/language.oop5.static.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51627 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51627&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51627&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51627&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51627&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51627&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51627&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#87546) next »