What is the difference between the following two ways to invoke a method in a class?
1
class MyClass { public function myfunc() { // ... }}$myclass = new MyClass;$myclass->myfunc();
2
class MyClass { public static function myfunc() { // ... }}MyClass::myfunc();
One is to instantiate it before invoking it, and the other is to declare the static method directly and invoke it directly. What is the difference between the two? Under what circumstances should they be used?
Reply content:
What is the difference between the following two ways to invoke a method in a class?
1
class MyClass { public function myfunc() { // ... }}$myclass = new MyClass;$myclass->myfunc();
2
class MyClass { public static function myfunc() { // ... }}MyClass::myfunc();
One is to instantiate it before invoking it, and the other is to declare the static method directly and invoke it directly. What is the difference between the two? Under what circumstances should they be used?
Popular understanding is:
The first can be used to $this->a; self::$a; static::$a; $this->a(); self::a(); static::a() obtain the relevant data and methods of the current class.
The second is self::$a; static::$a; self::a(); static::a() to obtain the relevant static data and static methods of the current class only in the same way.
staticIt cannot be used because the current object is not instantiated.
If an object a) has a tool-type method and B) is not dependent on an instance of the object, then it is best to use a static method.
But in real-world development, A is more weighted, that is, if possible, for a really widely used tool-based approach, developers might use a variety of methods to make it static, such as
public static function getTotal(array $numbers) { $self = new self(); return $self->getTotalNumber($numbers);}
Just write a few lines of code for the call. There is no so-called good or bad, depends on the specific situation.
In addition, the single-piece mode of the object is more common static methods, the root cause of the same, not specifically explained.