Mr A
Mr A

Reputation: 1385

Difference in Class Calling PHP

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.

Upvotes: 0

Views: 868

Answers (3)

Ben Graham
Ben Graham

Reputation: 2099

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

Upvotes: 3

Savageman
Savageman

Reputation: 9487

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.

Upvotes: 0

Gapton
Gapton

Reputation: 2134

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()

Upvotes: 0

Related Questions