> and ::

Possible Duplicate:
In PHP, whats the difference between :: and ->?

In PHP, what is the main difference of while calling a function() inside a class with arrow -> and Scope Resolution Operator :: ?

For more clearance, the difference between:

$name = $foo->getName();
$name = $foo::getName();

What is the main profit of Scope Resolution Operator :: ?


$name = $foo->getName();

This will invoke a member or static function of the object $foo , while

$name = $foo::getName();

will invoke a static function of the class of $foo . The 'profit', if you wanna call it that, of using :: is being able to access static members of a class without the need for an object instance of such class. That is,

$name = ClassOfFoo::getName();

  • -> is called to access a method of an instance (or a variable of an instanciated object)
  • :: is used to access static functions of an uninstanced object

  • They are for different function types. -> is always used on an object for static and non-static methods (though I don't think it's good practice use -> for static methods). :: is only used for static methods and can be used on objects (as of PHP 5.3) and more importantly classes .

    <?php
    
    class aClass {
        static function aStaticMethod() {}
        function aNormalMethod() {}
    }
    
    $obj = new aClass();
    $obj->aNormalMethod(); //allowed
    $obj->aStaticMethod(); //allowed
    $obj::aStaticMethod(); //allowed as of PHP 5.3
    $class_name = get_class( $obj );
    $class_name::aStaticMethod(); //long hand for $obj::aStaticMethod()
    aClass::aStaticMethod(); //allowed
    //aClass::aNormalMethod(); //not allowed
    //aClass->aStaticMethod(); //not allowed
    //aClass->aNormalMethod(); //not allowed
    
    链接地址: http://www.djcxy.com/p/58010.html

    上一篇: ::和之间的区别

    下一篇: >和::