note 84050 modified in language.constants.predefined by rquadling
| From: | rquadling@php.net | Date: | Fri, 18 Sep 2009 11:37:59 +0000 |
| Subject: | note 84050 modified in language.constants.predefined by rquadling | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-160826@lists.php.net to get a copy of this message | ||
We need an eighth magic constant, something along the lines of __STATIC__. This should return the
name of the class from which a static method was called, regardless of where in the inheritance tree
the method was defined.
PHP 5.3 has the new use of the static keyword which will help, but it isn't perfect. You still
have to repeat yourself frequently.
For example, trying to implement Active Record:
<?php
// In PHP 5.3
class Model
{
public static function find()
{
echo static::$class;
}
}
class Product extends Model
{
protected static $class = __CLASS__;
}
class User extends Model
{
protected static $class = __CLASS__;
}
Product::find(); // "Product"
User::find(); // "User"
?>
<?php
// With __STATIC__ keyword. (Would be better.)
class Model
{
public static function find()
{
echo __STATIC__;
}
}
class Product extends Model {}
class User extends Model {}
Product::find(); // "Product"
User::find(); // "User"
?>
[EDITED : Use get_called_class()]
--was--
We need an eighth magic constant, something along the lines of __STATIC__. This should return the
name of the class from which a static method was called, regardless of where in the inheritance tree
the method was defined.
PHP 5.3 has the new use of the static keyword which will help, but it isn't perfect. You still
have to repeat yourself frequently.
For example, trying to implement Active Record:
<?php
// In PHP 5.3
class Model
{
public static function find()
{
echo static::$class;
}
}
class Product extends Model
{
protected static $class = __CLASS__;
}
class User extends Model
{
protected static $class = __CLASS__;
}
Product::find(); // "Product"
User::find(); // "User"
?>
<?php
// With __STATIC__ keyword. (Would be better.)
class Model
{
public static function find()
{
echo __STATIC__;
}
}
class Product extends Model {}
class User extends Model {}
Product::find(); // "Product"
User::find(); // "User"
?>
http://php.net/manual/en/language.constants.predefined.php