PHP에서 메서드에 액세스하는 방법에는 두 가지가 있는데, 차이점은 무엇입니까?
$response->setParameter('foo', 'bar');
그리고.
sfConfig::set('foo', 'bar');
내 생각엔->
(보다 큰 기호 또는 쉐브론이 있는 기호)는 변수의 함수에 사용됩니다.::
(double colon)은 클래스 기능에 사용됩니다.맞습니까?
이요?=>
할당 연산자는 어레이 내의 데이터를 할당하는 데만 사용됩니까?이것은, 의 대조를 이루고 있는가.=
변수 인스턴스화 또는 수정에 사용되는 할당 연산자
질문에 대한 답변
왼쪽 부분이 오브젝트 인스턴스일 경우->
. 그 이외의 경우는::
.
즉,->
는 주로 인스턴스 멤버에 액세스하기 위해 사용됩니다(스태틱멤버에 액세스하기 위해서도 사용할 수 있습니다만, 이러한 사용은 권장되지 않습니다).::
는 보통 스태틱멤버에 액세스하기 위해 사용됩니다(단, 일부 특수한 경우에는 인스턴스 멤버에 액세스하기 위해 사용됩니다).
일반적으로는::
스코프 해결에 사용되며 클래스 이름 중 하나를 가질 수 있습니다.parent
,self
또는 (PHP 5.3의 경우)static
왼쪽입니다. parent
사용되는 클래스의 슈퍼클래스의 범위를 말합니다.self
사용되는 클래스의 범위를 말합니다.static
는 “called scope”(최신 스태틱바인딩 참조)를 나타냅니다.
규칙상 콜은::
는 다음과 같은 경우에만 인스턴스 콜입니다.
- 타깃 메서드가 스태틱으로 선언되지 않았습니다.
- 콜 시 호환되는 오브젝트콘텍스트가 존재하기 때문에 다음 조건이 충족되어야 합니다.
- 콜은, 다음의 콘텍스트로부터 행해집니다.
$this
존재하다 - 의 계급
$this
는 호출되는 메서드의 클래스 또는 하위 클래스 중 하나입니다.
- 콜은, 다음의 콘텍스트로부터 행해집니다.
예제:
class A {
public function func_instance() {
echo "in ", __METHOD__, "n";
}
public function callDynamic() {
echo "in ", __METHOD__, "n";
B::dyn();
}
}
class B extends A {
public static $prop_static = 'B::$prop_static value';
public $prop_instance = 'B::$prop_instance value';
public function func_instance() {
echo "in ", __METHOD__, "n";
/* this is one exception where :: is required to access an
* instance member.
* The super implementation of func_instance is being
* accessed here */
parent::func_instance();
A::func_instance(); //same as the statement above
}
public static function func_static() {
echo "in ", __METHOD__, "n";
}
public function __call($name, $arguments) {
echo "in dynamic $name (__call)", "n";
}
public static function __callStatic($name, $arguments) {
echo "in dynamic $name (__callStatic)", "n";
}
}
echo 'B::$prop_static: ', B::$prop_static, "n"; echo 'B::func_static(): ', B::func_static(), "n"; $a = new A; $b = new B; echo '$b->prop_instance: ', $b->prop_instance, "n"; //not recommended (static method called as instance method): echo '$b->func_static(): ', $b->func_static(), "n";
echo '$b->func_instance():', "n", $b->func_instance(), "n";
/* This is more tricky
* in the first case, a static call is made because $this is an
* instance of A, so B::dyn() is a method of an incompatible class
*/ echo '$a->dyn():', "n", $a->callDynamic(), "n"; /* in this case, an instance call is made because $this is an
* instance of B (despite the fact we are in a method of A), so
* B::dyn() is a method of a compatible class (namely, it's the
* same class as the object's)
*/ echo '$b->dyn():', "n", $b->callDynamic(), "n";
출력:
B::$prop_static:B::$prop_static 값 B::func_static():B::func_static $b->prop_instance:B::$prop_instance 값 $b->func_static():B:func_static $b->func_instance():A:func_instance $a->dynamic (A:func_instance $a->dynamic)의 func_instatic (B:func_instatic)
::
는 스태틱 컨텍스트에서 사용됩니다.즉, 일부 메서드 또는 속성이 스태틱으로 선언된 경우:
class Math {
public static function sin($angle) {
return ...;
} }
$result = Math::sin(123);
또,::
operator(Scope Resolution Operator, a.k.a Paamayim Nekudotayim)는 부모 클래스의 메서드/속성을 호출할 때 다이내믹콘텍스트에서 사용됩니다.
class Rectangle {
protected $x, $y;
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
} }
class Square extends Rectangle {
public function __construct($x) {
parent::__construct($x, $x);
} }
->
는 다이내믹 컨텍스트에서 사용됩니다.즉, 일부 클래스의 인스턴스를 처리할 때 다음과 같이 됩니다.
class Hello {
public function say() {
echo 'hello!';
} }
$h = new Hello(); $h->say();
덧붙여서, OOP 경험이 없을 때는 Symfony를 사용하는 것은 좋지 않다고 생각합니다.
실제로 이 기호에 의해 다른 초기화에 의존하지 않고 정적인 클래스 메서드를 호출할 수 있습니다.
class Test {
public $name;
public function __construct() {
$this->name = 'Mrinmoy Ghoshal';
}
public static function doWrite($name) {
print 'Hello '.$name;
}
public function write() {
print $this->name;
} }
여기에서는,doWrite()
함수는 다른 메서드 또는 변수에 의존하지 않으며 정적 메서드입니다.그렇기 때문에 이 클래스의 오브젝트를 초기화하지 않고 이 연산자에 의해 이 메서드를 호출할 수 있습니다.
Test::doWrite('Mrinmoy');
// Output: Hello Mrinmoy.
하지만 전화하고 싶다면write
이렇게 하면 초기화에 의존하기 때문에 오류가 발생합니다.
그=>
연산자는 관련 배열에서 키와 값의 쌍을 할당하는 데 사용됩니다.예를 들어 다음과 같습니다.
$fruits = array(
'Apple'
=> 'Red',
'Banana' => 'Yellow' );
의미가 비슷해요.foreach
스테이트먼트:
foreach ($fruits as $fruit => $color)
echo "$fruit is $color in color.";
정적 메서드와 인스턴스화된 메서드 및 속성 간의 차이는 PHP 5에서 OOP PHP로 시작하는 사용자에게 가장 큰 장애물 중 하나로 보입니다.
이중 콜론 연산자(히브리어 – trivia에서는 Paamayim Nekudotayim이라고 함)는 정적 컨텍스트에서 객체 또는 속성을 호출할 때 사용됩니다.이는 개체의 인스턴스가 아직 생성되지 않았음을 의미합니다.
화살표 연산자는 반대로 오브젝트 인스턴스의 참조에서 메서드 또는 속성을 호출합니다.
정적 메서드는 삽입된 테이블 ID로 반환 값을 설정한 다음 생성자를 사용하여 행 ID로 개체를 인스턴스화할 수 있으므로 작성 및 삭제 메서드를 위해 데이터베이스에 연결된 개체 모델에서 특히 유용합니다.