Difference in Class Calling PHP

☆樱花仙子☆ 提交于 2019-12-11 15:23:03

问题


With learning fuelPHP, I am introduced on calling classes using scope resolution, or :: in sense. Typically, when we call a method in a class we do this ...

$myclass = new myclass();
$myclass->mymethod();

On fuel, methods are usually called in this manner ...

myclass::mymethod();

I was wondering if there are any difference between the two? Is the scope resolution is something of an update on 5.3 as well ... if not, which one is ideal, or when should I use these.

Thanks.


回答1:


The scope resolution operator is used to access either class constants like ::const, static variables like ::$var or call static methods like ::method().

See http://php.net/manual/en/language.oop5.static.php

Static methods can be called without having an instance of the class they are defined in. They're defined in that class with the static keyword.

For example, one of CakePHP's static methods is defined like this:

class ClassRegistry {
    // ...
    public static function &getInstance() {
        // ...
    }
}

... which you can call like ClassRegistry::getInstance().

Without the static keyword, you'd need an instance of the ClassRegistry class to call that function.

You can read more here, especially about why using static methods in your own code can sometimes be a bad idea: http://kore-nordmann.de/blog/0103_static_considered_harmful.html




回答2:


I am not sure how would myclass::mymethod(); work, since I use such syntax only when I am calling a STATIC class.

MyClass::DoSomething();

would call a static method named DoSomething()

while

$instance = new MyClass();

$instance->DoSomething();

would call the instance method.

I have not tested it but I believe you will run into an error if you do $instance::DoSomething()




回答3:


I think the best way to understand why there is a static call and what it does behind the scene is to check this FuelPHP blog's entry: http://fuelphp.com/blog/2011/05/why-did-you-do-that

The obvious difference is that the first solution $myObject->myMethod() it's a dynamic call : you need an instance to execute myMethod().

In the second solution, MyClass::myMethod() is a static call. The class acts as a sort of namespace where a function belong. You don't need an instance for that.



来源:https://stackoverflow.com/questions/13043537/difference-in-class-calling-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!