note 99542 added to language.oop5.static
| From: | Mirco at osu1 dot php dot net | Date: | Mon, 23 Aug 2010 17:16:38 +0000 |
| Subject: | note 99542 added to language.oop5.static | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171951@lists.php.net to get a copy of this message | ||
The simplest static constructor.
Because php does not have a static constructor and you may want to initialize static class vars,
there is one easy way, just call your own function directly after the class definition.
for example.
<?php
function Demonstration()
{
return 'This is the result of demonstration()';
}
class MyStaticClass
{
//public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
public static $MyStaticVar = null;
public static function MyStaticInit()
{
//this is the static constructor
//because in a function, everything is allowed, including initializing using other functions
self::$MyStaticVar = Demonstration();
}
} MyStaticClass::MyStaticInit(); //Call the static constructor
echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
----
Server IP: 69.147.83.197
Probable Submitter: 95.36.102.147
----
Manual Page -- http://www.php.net/manual/en/language.oop5.static.php
Edit -- https://master.php.net/note/edit/99542
Del: integrated -- https://master.php.net/note/delete/99542/integrated
Del: useless -- https://master.php.net/note/delete/99542/useless
Del: bad code -- https://master.php.net/note/delete/99542/bad+code
Del: spam -- https://master.php.net/note/delete/99542/spam
Del: non-english -- https://master.php.net/note/delete/99542/non-english
Del: in docs -- https://master.php.net/note/delete/99542/in+docs
Del: other reasons-- https://master.php.net/note/delete/99542
Reject -- https://master.php.net/note/reject/99542
Search -- https://master.php.net/manage/user-notes.php