note 51627 deleted from language.oop5.static by cmb

From: Date: Sun, 01 Sep 2019 07:24:11 +0000
Subject: note 51627 deleted from language.oop5.static by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212049@lists.php.net to get a copy of this message
Note Submitter: erikzoltan NOSPAM at msn NOSPAM dot com ---- 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); ?>

« previous php.notes (#212049) next »