开发者

difference between :: and -> in calling class's function in php

I have seen function called from php classes with :: or ->.

eg:

$classinstance::function or $classinstance->function

whats开发者_如何学JAVA the difference?


:: is used for scope resolution, accessing (typically) static methods, variables, or constants, whereas -> is used for invoking object methods or accessing object properties on a particular object instance.

In other words, the typical syntax is...

ClassName::MemberName

versus...

$Instance->MemberName

In the rare cases where you see $variable::MemberName, what's actually going on there is that the contents of $variable are treated as a class name, so $var='Foo'; $var::Bar is equivalent to Foo::Bar.

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

http://www.php.net/manual/language.oop5.paamayim-nekudotayim.php


The :: syntax means that you are calling a static method. Whereas the -> is non-static.

MyClass{

  public function myFun(){  
  }

  public static function myStaticFun(){
  }

}

$obj = new MyClass();

// Notice how the two methods must be called using different syntax
$obj->myFun();
MyClass::myStaticFun();


Example:

class FooBar {
    public function sayHi() { echo 'Hi!'; }
    public /* --> */ static /* <-- */ function sayHallo() { echo 'Hallo!'; }
}

// object call (needs an instance, $foobar here)
$foobar = new FooBar;
$foobar->sayHi();

// static class call, no instance required
FooBar::sayHallo(); // notice I use the plain classname here, not $foobar!

// As of PHP 5.3 you can write:
$nameOfClass = 'FooBar'; // now I store the classname in a variable
$nameOfClass::sayHallo(); // and call it statically

$foobar::sayHallo(); // This will not work, because $foobar is an class *instance*, not a class *name*


::function is for static functions, and should actually be used as:

class::function() rather than $instance::function() as you suggest.

You can also use

class::function()

in a subclass to refer to parent's methods.


:: is normally used for calling static methods or Class Constants. (in other words, you don't need to instantiate the object with new) in order to use the method. And -> is when you've already instantiated a object.

For example:

Validation::CompareValues($val1, $val2);

$validation = new Validation;
$validation->CompareValues($val1, $val2);

As a note, any method you try to use as static (or with ::) must have the static keyword used when defining it. Read the various PHP.net documentation pages I've linked to in this post.


With :: you can access constants, attributes or methods of a class; the variables and methods need to be declared as static, otherwise they do belong to an instance and not to the class.

And with -> you can access attributes or methods of an instance of a class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜