Home > Article > Backend Development > PHP object-oriented notes - 123 Illustration of static properties and static methods
The content introduced in this article is the content in PHP object-oriented, 123 diagrams of static properties and static methods, now shared with everyone, friends in need can refer to it
/*
In properties , and
add static modification before the method, this is called static attribute/static method.
Static attribute
Static attribute is stored in the class space
1. Class declaration is completed , the attribute already exists and does not need to depend on the object for access.
2. There is only one class in the memory, so there is only one static attribute.
*/
class Human { static public $head = 1; public function changeHead() { Human::$head = 9; } public function getHead() { return Human::$head; } }echo Human::$head; //1// 静态属性的访问方法echo '<br >';// 静态属性只有一个,为所有的对象的共享.$m1 = new Human();$m1->changeHead();$m2 = new Human();$m3 = new Human();echo $m2->getHead(),'<br >'; //9echo $m3->getHead(),'<br >'; //9
/*
Static method
Ordinary methods, stored within the class, only have one copy
Static methods, also stored within the class, have only one copy
The difference is:
Ordinary methods require objects to mobilize and need to bind $this
That is, ordinary methods must have objects and are mobilized with objects
And static methods do not belong to which The object belongs to the class, so there is no need to bind $this.
That is, the static method can be mobilized through the class name.
*/
class Human2 { public $name = '张三'; static public function cry() { echo '5555'; } public function eat() { echo '吃饭'; } public function intro() { echo $this->name; } }// 此时一个对象都没有Human2::cry();// 下面这个eat是非静态方法,应由对象来调用Human2::eat();/* 报错提示: Strict standards: Non-static method Human2::eat() should not be called statically */echo '<br >';//Human2::intro();/* 直接报错: Fatal error: Using $this when not in object context */
/*
Summary:
As analyzed above, in fact, non-static methods cannot be statically called by class names.
*/
$lisi = new Human2();$lisi->cry(); //5555
/*
Class->Access->Static method can
Class->Dynamic method If there is no this in the method, it is seriously not supported. It cannot be explained logically.
Object-> Access dynamic methods can
Object->Static methods can
*/
Related recommendations:
php object-oriented introduction to inheritance, polymorphism, and encapsulation
Overview of php object-oriented design principles
The above is the detailed content of PHP object-oriented notes - 123 Illustration of static properties and static methods. For more information, please follow other related articles on the PHP Chinese website!