Home >Backend Development >PHP Problem >How do static methods call non-static methods in PHP classes?
Static methods in PHP classes call non-static methods: First, in the static method in the class, the object needs to be instantiated; then the method in the class is called, the code is [self::staticFun(); A:: staticFun()].
Static methods in PHP classes call non-static methods:
Non-static methods call static methods: Yesself
or the class name plus ::
is called
as in the following case:
<?php class A{ public function noneStaticFun(){ echo __CLASS__." none static function<br/>"; } public static function staticFun(){ echo __CLASS__." static function<br/>"; //静态方法调用非静态方法,需要实例化对象然后再调用对象中的非静态方法 (new A())->noneStaticFun(); } public function testCallStaticFun(){ echo "call static function<br/>"; //调用本类的静态方法,使用 self关键字或者类名 self::staticFun(); //A::staticFun(); //也可以使用这种方式 //调用其它类的静态方法,直接使用类名::方法名的形式调用 B::myStaticFun(); } } class B{ public static function myStaticFun(){ echo __CLASS__." static function<br/>"; } } //演示 $testA = new A(); $testA->testCallStaticFun(); A::staticFun();
Running result:
call static function A static function A none static function B static function A static function A none static function
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of How do static methods call non-static methods in PHP classes?. For more information, please follow other related articles on the PHP Chinese website!