note 99705 added to language.oop5.final

From: Date: Tue, 31 Aug 2010 20:37:51 +0000
Subject: note 99705 added to language.oop5.final
Groups: php.notes 
Request: Send a blank email to php-notes+get-172212@lists.php.net to get a copy of this message
"Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'." http://php.net/manual/en/language.oop5.constants.php This is more or less true, regardless of the fact that constant (being defined at class level or not) in PHP are only scalar (int, string, etc) while in Java they may be pure object (ex: java.awat.Color.BLACK). The only possible solution of having such kind of constant is : <?php class Bar {...} class Foo { public static $FOOBAR; static function __init() { static $init = false; if ($init) throw new Exception('Constants were already initialized'); self::$FOOBAR = new Bar(); $init = true; } } Foo::__init(); ?> That said, perhaps it is useless unless PHP automatically calls the __init() method. However, one alternative that could be done in certain case is this : <?php function __autoload($className) { ... require the file where the class is ... if (interface_exists($className, false)) return; if (class_exists($className, false)) { $rc = new ReflectionClass($className); if (!$rc->hasMethod('__init')) return; $m = $rc->getMethod('__init'); if (!($m->isStatic() && $m->isPrivate())) { throw new Exception($className . ' __init() method must be private and static !'); } $m->invoke(null); return; } throw new Exception('Class or interface not found ' . $className); } ?> This can only work when one class is defined per file, since we are assured that __autoload() will be called to load the file containing the class. eg: test2.php: <?php class B { public static $X; private static function __init() { echo 'B', "\n"; self::$X = array(1, 2); } } class A { public static $Y; private static function __init() { echo 'A', "\n"; self::$Y = array(3, 4); } } ?> test.php: <?php function __autoload($n) { if ($n == 'A' || $n == 'B') require 'test2.php'; ... do our __init() trick ... } var_dump(B::$X); // shows B, then array(2) (1, 2) var_dump(A::$Y); // shows NULL. ?> ---- Server IP: 195.221.21.36 Probable Submitter: 90.35.242.215 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.final.php Edit -- https://master.php.net/note/edit/99705 Del: integrated -- https://master.php.net/note/delete/99705/integrated Del: useless -- https://master.php.net/note/delete/99705/useless Del: bad code -- https://master.php.net/note/delete/99705/bad+code Del: spam -- https://master.php.net/note/delete/99705/spam Del: non-english -- https://master.php.net/note/delete/99705/non-english Del: in docs -- https://master.php.net/note/delete/99705/in+docs Del: other reasons-- https://master.php.net/note/delete/99705 Reject -- https://master.php.net/note/reject/99705 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172212) next »