0302 PHP OOP
소스코드 보면서 궁금했던 것들을 찾아본 뒤 기록.
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.
Author And Source
이 문제에 관하여(0302 PHP OOP), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@cocokaribou/0302-PHP저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)