>myMethod(); vs MyClass::myMethod();

Possible Duplicate:
In PHP, whats the difference between :: (double colon) and -> (arrow)?

I just had a quick question about what seems to me to be two different ways of doing the same thing. If there are difference other than syntax, please explain what they are.

We'll assume we have a class called MyClass with a method called myMethod . What's in them probably isn't relevant, because we're just going to be calling them from another file.

Here's the first way that I know of (there may be other ways - these are what I know):

$myvar = new MyClass();
$myvar->myMethod();

And the second way:

MyClass::myMethod();

If there are other ways, particularly better ways, by all means elaborate on them, but the main question here is the difference between these two examples.

Thanks!


Use MyClass::myMethod(); with static methods. And $myvar->myMethod(); in other cases.

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


The first one executes a method on an object. The second one executes a method at class level (a classmethod).

They are both different things.


$myObj = new MyClass();
$myObj->myMethod();

This is an instance method call. You are calling it with an object reference (passed as $this inside the method definition) that you just created in the previous line.

MyClass::myMethod();

This is a static method call. You are calling it as is, with no reference. Only static methods can should be called this way.


As pointed out in the comments, instance methods can be called with the :: syntax, but using $this in any way will generate a runtime error. This is also something you wouldn't normally do. I can't think of an scenario where this is in any way useful. So stick to the above.

链接地址: http://www.djcxy.com/p/58016.html

上一篇: 初学者的帮助

下一篇: > myMethod的(); vs MyClass :: myMethod();