0302 PHP OOP

10599 단어 phpTILTIL

소스코드 보면서 궁금했던 것들을 찾아본 뒤 기록.

Scope Resolution Operator(::)

🔗

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

:: vs ->

🔗
Simply put, :: is for class-level properties, and -> is for object-level properties.
If the property belongs to the class, use ::
If the property belongs to an instance of the class, use ->

class Tester
{
  public $foo;
  const BLAH;

  public static function bar(){}
}

$t = new Tester;
$t->foo;
Tester::bar();
Tester::BLAH;



self vs $this

🔗

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

The example of correct usage of $this and self for non-static and static member variables.

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?>

output: 1 2

(...)
Here is an example of polymorphism with $this for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

output: Y::foo()
Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

output: X::foo()

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

좋은 웹페이지 즐겨찾기