Home >Backend Development >PHP Tutorial >A newbie has a question about classes

A newbie has a question about classes

WBOY
WBOYOriginal
2016-09-15 11:31:001190browse

What is the difference between the following two ways of calling methods in a class?

1

<code>class MyClass {
    public function myfunc() {
        // ...
    }
}

$myclass = new MyClass;
$myclass->myfunc();</code>

2

<code>class MyClass {
    public static function myfunc() {
        // ...
    }
}

MyClass::myfunc();</code>

One is to instantiate it first and then call it, the other is to directly declare the static method and call it directly. What's the difference between these two? Under what circumstances should they be used?

Reply content:

What is the difference between the following two ways of calling methods in a class?

1

<code>class MyClass {
    public function myfunc() {
        // ...
    }
}

$myclass = new MyClass;
$myclass->myfunc();</code>

2

<code>class MyClass {
    public static function myfunc() {
        // ...
    }
}

MyClass::myfunc();</code>

One is to instantiate it first and then call it, the other is to directly declare the static method and call it directly. What's the difference between these two? Under what circumstances should they be used?

The popular understanding is:

The first method can be used$this->a; self::$a; static::$a; $this->a(); self::a(); static::a()etc. Method to obtain relevant data and methods of the current class

The second method can only use self::$a; static::$a; self::a(); static::a() to obtain the relevant static data and static methods of the current class

staticYou cannot use this inside because the current object has not been instantiated.

If an object a) has a utility method and b) does not depend on an instance of the object then static methods are best suited.

But in actual development, a) has a higher weight, that is, if possible, for a tool method that is indeed widely used, developers may use various methods to make it static, such as

<code>public static function getTotal(array $numbers) {
    $self = new self();
    return $self->getTotalNumber($numbers);
}</code>

Just to save a few lines of code when calling. It doesn’t matter if it’s good or bad, it depends on the circumstances.

In addition, static methods are also more common in singleton mode objects. The root cause is the same as above and will not be explained in detail.

Statement:
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