라이브러리
[PHP] Closure::bind - 특정 바인딩된 객체와 클래스 범위를 갖는 클로저를 복제합니다.
Closure::bind
PHP 5.3에서 Closure 클래스가 도입되었습니다. Closure 클래스는 익명 함수를 나타내는 클래스입니다. Closure::bind 메서드는 익명 함수를 특정 객체에 바인딩하는 메서드입니다.
Closure::bind 메서드의 사용
Closure::bind 메서드는 익명 함수를 특정 객체에 바인딩하는 메서드입니다. 이 메서드는 익명 함수의 `this` 키워드가 특정 객체를 참조하도록 합니다.
예제
#hostingforum.kr
php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHello() {
$greet = function() {
echo "Hello, my name is " . $this->name . "!";
};
$greet->bindTo($this, 'Person');
$greet();
}
}
$person = new Person('John');
$person->sayHello(); // Hello, my name is John!
위 예제에서, `sayHello` 메서드 내부의 익명 함수는 `$this` 키워드를 사용하여 `Person` 객체의 `name` 프로퍼티를 참조합니다. 그러나 익명 함수는 `Person` 객체에 바인딩되지 않았기 때문에 `$this` 키워드는 `Person` 객체를 참조하지 않습니다. 따라서 익명 함수는 `sayHello` 메서드의 `$this`를 참조합니다.
`bindTo` 메서드를 사용하여 익명 함수를 `Person` 객체에 바인딩하면, `$this` 키워드는 `Person` 객체를 참조합니다. 따라서 익명 함수는 `Person` 객체의 `name` 프로퍼티를 참조합니다.
bindTo 메서드의 매개 변수
`bindTo` 메서드는 두 개의 매개 변수를 받습니다.
* `$object`: 바인딩할 객체입니다.
* `$class`: 바인딩할 클래스입니다. (선택 사항)
`$class` 매개 변수는 `$object`가 `$class`의 인스턴스인지 확인하는 데 사용됩니다. 만약 `$object`가 `$class`의 인스턴스가 아니라면 `TypeError` 예외가 발생합니다.
예제
#hostingforum.kr
php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHello() {
$greet = function() {
echo "Hello, my name is " . $this->name . "!";
};
$greet->bindTo($this, 'Person');
$greet();
}
}
$person = new Person('John');
$greet = $person->sayHello;
$greet(); // Hello, my name is John!
// TypeError 예외 발생
$greet = function() {
echo "Hello, my name is " . $this->name . "!";
};
$greet->bindTo(new stdClass(), 'Person'); // TypeError: Argument 1 passed to Person::sayHello() must be an instance of Person, instance of stdClass given
위 예제에서, `$greet` 변수는 `sayHello` 메서드의 익명 함수를 참조합니다. `$greet` 변수를 호출하면 익명 함수가 호출됩니다. 익명 함수는 `$this` 키워드를 사용하여 `Person` 객체의 `name` 프로퍼티를 참조합니다.
`bindTo` 메서드를 사용하여 익명 함수를 `Person` 객체에 바인딩하면, `$this` 키워드는 `Person` 객체를 참조합니다. 따라서 익명 함수는 `Person` 객체의 `name` 프로퍼티를 참조합니다.
만약 `$greet` 변수를 호출할 때 `$this` 키워드가 `Person` 객체를 참조하지 않는 경우, `TypeError` 예외가 발생합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.