Home  >  Article  >  Backend Development  >  php--static keyword

php--static keyword

伊谢尔伦
伊谢尔伦Original
2016-11-23 14:11:37971browse

This page explains the use of static keyword to define static methods and properties. static can also be used to define static variables and late static binding.

Declaring a class attribute or method as static allows you to access it directly without instantiating the class. Static properties cannot be accessed through an object of a class that has been instantiated (but static methods can).

In order to be compatible with PHP 4, if no access control is specified, properties and methods default to public.

Since static methods do not need to be called through objects, the pseudo variable $this is not available in static methods.

Static properties cannot be accessed by objects through the -> operator.

Calling a non-static method statically will result in an E_STRICT level error.

Like all other PHP static variables, static properties can only be initialized to literals or constants, not expressions. So a static property can be initialized to an integer or an array, but it cannot be initialized to another variable or function return value, nor can it point to an object.

Example #1 Static property example

class Foo
{
    public static $my_static = 'foo';
    public function staticValue(){
        return self::$my_static;
    }
}
class Bar extends Foo
{
    public function fooStatic(){
        return parent::$my_static;
    }
}
print Foo::$my_static.&#39;<br>&#39;;
$foo = new Foo();
print $foo->staticValue().&#39;<br>&#39;;
print $foo->my_static.&#39;<br>&#39;;
print $foo::$my_static.&#39;<br>&#39;;
$classname = &#39;Foo&#39;;
print $classname::$my_static;
print Bar::$my_static.&#39;<br>&#39;;
$bar = new Bar();
print $bar->fooStatic().&#39;<br>&#39;;


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn