Home >Backend Development >PHP Problem >What are the differences between static calls and instantiated calls of PHP classes?
The differences are: 1. Static methods generate memory when the program starts, and instance methods generate memory while the program is running; 2. Static methods can be called directly, and instance methods must first generate an instance, and then call the method through the instance. ; 3. Static memory is continuous, and instances apply for discrete space, so it is not as fast as static methods, and static memory is limited.
There is only one static method. No matter how many times you call it, it is shared. There is no concept of object, so it cannot be used statically. Use $this to call in the method. If you have to call, you can only instantiate your own class
Instancing is different. Each instantiation is an object and has multiple.
Let’s use an example to understand
<?php Error_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........ 但是实例化的类是可以调用静态方法的。 */
<?php class A{ public $name = 'kangbazi'; public function bar(){ echo 'bar'.PHP_EOL; } public static function foo(){ echo self::$name.PHP_EOL;//报错 } } A::foo(); /* 静态方法不能调用非静态属性 。不能使用self::调用非静态属性。 */
Make a short summary:
The biggest difference is memory.
Static methods generate memory when the program starts, instance methods generate memory while the program is running,
So static methods can be called directly, instances The method must first generate an instance and call the method through the instance. The static speed is very fast, but if it is too much, it will occupy memory.
Any language operates on memory and disk. As for whether it is object-oriented, it is just a question of the software layer. The bottom layer is the same, but the implementation method is different.
Static memory is continuous because it is generated at the beginning of the program, and the instance applies for discrete space, so of course it is not as fast as the static method,
And static memory is limited, if there is too much, the program will not be able to start.
Recommended tutorial: "php tutorial"
The above is the detailed content of What are the differences between static calls and instantiated calls of PHP classes?. For more information, please follow other related articles on the PHP Chinese website!