Search code examples
phpoopscope-resolution

Different ways to access methods


I have seen that there are two different ways to access methods within a class. Are there any differences in behaviour, or are they purely alternative syntaxes for the same action?

$a = new A();
$a->foo();

A::foo();

Solution

  • You can't just use one or the other. :: is for static methods and variables, whereas -> is for instance methods and variables. This is "inspired" from C++ syntax.

    class A {
        public function __construct() {}
        public function foo() {}
    }
    $a = new A();
    $a->foo();
    // Or use the shorter "new A()->foo()";
    //   It won't return typeof(A), it will return what foo() returns.
    // The object will still be created, but the GC should delete the object
    

    or

    class A {
        public static function foo() {}
    }
    A::foo();
    

    According to DCoder, :: can be used for calling parent methods, but I don't know this for sure.

    class B {
        public function __construct() {}
        public function foo() {}
    }
    class A extends B {
        public function __construct() {
            // Code
            parent::__construct()
        }
        public function foo() {
            // Code
            parent::foo()
        }
    }