Home > Article > Backend Development > About the difference between PHP static method calls and instantiated class calls
The content of this article introduces the difference between PHP static method calls and instantiated class calls. Now I share it with you. Friends in need can refer to it
1. First, let’s clarify some points
Since there is only one copy of the static method in the memory, no matter how many times you call it, it is shared, and there is no concept of object, so you cannot use $this call in the static method. If you have to call it, you can only Instantiate your own class
But instantiation is different. Each instantiation is an object, and there are multiple objects in the memory
<?phpError_reporting (E_ALL|E_STRICT);class A{ public function bar(){ echo 'bar'.PHP_EOL; } public static function foo(){ echo 'foo'.PHP_EOL; } } A::bar();//会报错 A::foo();//正确 $obj = new A(); $obj -> foo();//正确
/* bar()是一个非静态方法,应该由对象来调用,但用静态来调用此方法也可以执行,而严格状态下,此方法会执行,同时报错, Strict Standards: Non-static method Human::easyeat() should not be called statically in........ 但是实例化的类是可以调用静态方法的。 */
<?phpclass A{ public $name = 'zongshuai'; public function bar(){ echo 'bar'.PHP_EOL; } public static function foo(){ echo self::$name.PHP_EOL;//报错 } } A::foo();/* 静态方法不能调用非静态属性 。不能使用self::调用非静态属性。*/
总结: 类》访问->静态方法(类的方法)->可以 类》访问->普通方法(对象的方法)->不可以(虽然方法里不用$this关键字时,可以!但不支持这种写法) 对象》访问》静态方法(类的方法)->可以 对象》访问》普通方法(对象的方法)->可以 相关推荐:
<a href="http://www.php.cn/php-weizijiaocheng-391759.html" target="_self">PHP调用京东联盟开普勒、宙斯API模板</a><br/><br/>
The above is the detailed content of About the difference between PHP static method calls and instantiated class calls. For more information, please follow other related articles on the PHP Chinese website!