Ключевое слово «static»
Эта страница описывает использование ключевого слова static для определения статических методов и свойств. static также может использоваться для определения статических переменных и позднего статического связывания. Для получения информации о таком применении ключевого слова static пользуйтесь вышеуказанными страницами.
Объявление свойств и методов класса статическими позволяет обращаться к ним без создания экземпляра класса. Атрибут класса, объявленный статическим, не может быть доступен посредством экземпляра класса (но статический метод может быть вызван).
В целях совместимости с PHP 4, сделано так, что если не использовалось определение области видимости, то член или метод будет рассматриваться, как если бы он был объявлен как public.
Так как статические методы вызываются без создания экземпляра класса, то псевдо-переменная $this не доступна внутри метода, объявленного статическим.
Доступ к статическим свойствам класса не может быть получен через оператор ->.
При попытке вызова нестатических методов статически выводится предупреждение уровня E_STRICT .
Как и любая другая статическая переменная PHP, статические свойства могут инициализироваться только используя литерал или константу, выражения же недопустимы. Таким образом вы можете инициализировать статическое свойство например целым числом или массивом, но не сможете указать другую переменную, результат вызова функции или объект.
Начиная с версии PHP 5.3.0 существует возможность ссылаться на класс используя переменную. Поэтому значение переменной в таком случае не может быть ключевым словом (например, self, parent и static).
Пример #1 Пример статического свойства
class Foo
public static $my_static = ‘foo’ ;
?php
public function staticValue () return self :: $my_static ;
>
>
class Bar extends Foo
public function fooStatic () return parent :: $my_static ;
>
>
$foo = new Foo ();
print $foo -> staticValue () . «\n» ;
print $foo -> my_static . «\n» ; // Не определено свойство my_static
print $foo :: $my_static . «\n» ; // Начиная с PHP 5.3.0
$classname = ‘Foo’ ;
print $classname :: $my_static . «\n» ; // Начиная с PHP 5.3.0
print Bar :: $my_static . «\n» ;
$bar = new Bar ();
print $bar -> fooStatic () . «\n» ;
?>
Пример #2 Пример статического метода
Foo :: aStaticMethod ();
$classname = ‘Foo’ ;
$classname :: aStaticMethod (); // Начиная с PHP 5.3.0
?>
Php public static var
It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public .
Note:
Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.
It’s also possible for interfaces to have constants . Look at the interface documentation for examples.
It’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self , parent and static ).
Note that class constants are allocated once per class, and not for each class instance.
Example #1 Defining and using a constant
class MyClass
const CONSTANT = ‘constant value’ ;
?php
function showConstant () echo self :: CONSTANT . «\n» ;
>
>
echo MyClass :: CONSTANT . «\n» ;
$classname = «MyClass» ;
echo $classname :: CONSTANT . «\n» ;
$class = new MyClass ();
$class -> showConstant ();
The special ::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:
Example #2 Namespaced ::class example
Example #3 Class constant expression example
const ONE = 1 ;
class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘The value of THREE is ‘ . self :: THREE ;
>
?>?php
Example #4 Class constant visibility modifiers, as of PHP 7.1.0
class Foo public const BAR = ‘bar’ ;
private const BAZ = ‘baz’ ;
>
echo Foo :: BAR , PHP_EOL ;
echo Foo :: BAZ , PHP_EOL ;
?>?php
Output of the above example in PHP 7.1:
bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
Note:
As of PHP 7.1.0 visibility modifiers are allowed for class constants.
User Contributed Notes 12 notes
it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class’ method:
abstract class dbObject
<
const TABLE_NAME = ‘undefined’ ;
public static function GetAll ()
$c = get_called_class ();
return «SELECT * FROM `» . $c :: TABLE_NAME . «`» ;
>
>
class dbPerson extends dbObject
const TABLE_NAME = ‘persons’ ;
>
class dbAdmin extends dbPerson
const TABLE_NAME = ‘admins’ ;
>
echo dbPerson :: GetAll (). «
» ; //output: «SELECT * FROM `persons`»
echo dbAdmin :: GetAll (). «
» ; //output: «SELECT * FROM `admins`»
As of PHP 5.6 you can finally define constant using math expressions, like this one:
class MyTimer const SEC_PER_DAY = 60 * 60 * 24 ;
>
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain.
A constant is a name for a value (but it’s NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.
So returned values from functions can’t be used, because they will return a value only at runtime.
Arrays can’t be used, because they are data structures that exist at runtime.
One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.
Think about some examples written by some before me:
1. const MY_ARR = «return array(\»A\», \»B\», \»C\», \»D\»);»;
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.
2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can’t work, of course. And it doesn’t make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.
3. Someone spoke about «dynamic» assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let’s take the proposed example:
/**
* Constants that deal only with the database
*/
class DbConstant extends aClassConstant <
protected $host = ‘localhost’ ;
protected $user = ‘user’ ;
protected $password = ‘pass’ ;
protected $database = ‘db’ ;
protected $time ;
function __construct () <
$this -> time = time () + 1 ; // dynamic assignment
>
>
?>
Those aren’t constants, those are properties of the class. Something like «this->time = time()» would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.
Conclusion: Don’t try to reinvent constants as variables. If constants don’t work, just use variables. Then you don’t need to reinvent methods to achieve things for what is already there.
I think it’s useful if we draw some attention to late static binding here:
class A const MY_CONST = false ;
public function my_const_self () return self :: MY_CONST ;
>
public function my_const_static () return static:: MY_CONST ;
>
>
class B extends A const MY_CONST = true ;
>
$b = new B ();
echo $b -> my_const_self ? ‘yes’ : ‘no’ ; // output: no
echo $b -> my_const_static ? ‘yes’ : ‘no’ ; // output: yes
?>
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.
const BAR = 1 ;
?>
# bar.php
require ‘foo.php’ ;
var_dump ( Foo \ BAR ); // => int(1)
?>
Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:
class a <
const CONST_INT = 10 ;
public function getSelf () return self :: CONST_INT ;
>
public function getThis () return $this :: CONST_INT ;
>
>
?>
And class b (which extends a)
class b extends a const CONST_INT = 20 ;
public function getSelf () return parent :: getSelf ();
>
public function getThis () return parent :: getThis ();
>
>
?>
Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.
print_r ( $b -> getSelf ()); //10
print_r ( $b -> getThis ()); //20