Home > Backend Development > PHP Tutorial > About the difference between PHP static method calls and instantiated class calls

About the difference between PHP static method calls and instantiated class calls

不言
Release: 2023-03-23 10:00:01
Original
2724 people have browsed it

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


About the difference between PHP static method calls and instantiated class calls

<?phpError_reporting (E_ALL|E_STRICT);class A{    
    public function bar(){        echo &#39;bar&#39;.PHP_EOL;
    }    public static function foo(){        echo &#39;foo&#39;.PHP_EOL;
    }
}

A::bar();//会报错
A::foo();//正确
$obj = new A();
$obj -> foo();//正确
Copy after login
/* 
  bar()是一个非静态方法,应该由对象来调用,但用静态来调用此方法也可以执行,而严格状态下,此方法会执行,同时报错, 
  Strict Standards: Non-static method Human::easyeat() should not be called statically in........
  但是实例化的类是可以调用静态方法的。
*/
Copy after login

About the difference between PHP static method calls and instantiated class calls


About the difference between PHP static method calls and instantiated class calls

<?phpclass A{    public $name = &#39;zongshuai&#39;;    public function bar(){        echo &#39;bar&#39;.PHP_EOL;
    }    public static function foo(){        echo self::$name.PHP_EOL;//报错
    }
}

A::foo();/*
    静态方法不能调用非静态属性 。不能使用self::调用非静态属性。*/
Copy after login

About the difference between PHP static method calls and instantiated class calls

总结: 
类》访问->静态方法(类的方法)->可以 
类》访问->普通方法(对象的方法)->不可以(虽然方法里不用$this关键字时,可以!但不支持这种写法)
对象》访问》静态方法(类的方法)->可以 
对象》访问》普通方法(对象的方法)->可以
相关推荐:
Copy after login
<a href="http://www.php.cn/php-weizijiaocheng-391759.html" target="_self">PHP调用京东联盟开普勒、宙斯API模板</a><br/><br/>             
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template