라이브러리
[PHP] Closure::bindTo - 새로운 바인딩된 객체와 클래스 범위로 클로저를 복제합니다.
Closure::bindTo
================
PHP의 Closure::bindTo 메소드는 Closure 객체를 특정 객체에 바인딩하는 메소드입니다. 바인딩된 Closure 객체는 바인딩된 객체의 속성과 메소드를 사용할 수 있습니다.
바인딩된 Closure 객체의 특징
* 바인딩된 Closure 객체는 바인딩된 객체의 속성과 메소드를 사용할 수 있습니다.
* 바인딩된 Closure 객체는 바인딩된 객체의 scope를 사용합니다.
* 바인딩된 Closure 객체는 바인딩된 객체의 static 속성을 사용할 수 없습니다.
예제
#hostingforum.kr
php
class MyClass {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHello() {
echo "Hello, " . $this->name . "!
";
}
}
$myClass = new MyClass("John");
$closure = function() use ($myClass) {
$myClass->sayHello();
};
$closure->bindTo($myClass, 'MyClass');
$closure(); // Hello, John!
위 예제에서, Closure 객체는 MyClass 객체에 바인딩되어 있습니다. 바인딩된 Closure 객체는 MyClass 객체의 속성과 메소드를 사용할 수 있습니다.
바인딩된 Closure 객체의 scope
바인딩된 Closure 객체는 바인딩된 객체의 scope를 사용합니다. 예를 들어, 다음 예제에서, Closure 객체는 MyClass 객체의 scope를 사용합니다.
#hostingforum.kr
php
class MyClass {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHello() {
echo "Hello, " . $this->name . "!
";
}
public function getScope() {
return $this;
}
}
$myClass = new MyClass("John");
$closure = function() use ($myClass) {
$scope = $myClass->getScope();
echo "Scope: " . $scope->name . "
";
};
$closure->bindTo($myClass, 'MyClass');
$closure(); // Scope: John
위 예제에서, Closure 객체는 MyClass 객체의 scope를 사용하여 MyClass 객체의 속성을 사용할 수 있습니다.
바인딩된 Closure 객체의 static 속성
바인딩된 Closure 객체는 바인딩된 객체의 static 속성을 사용할 수 없습니다. 예를 들어, 다음 예제에서, Closure 객체는 MyClass 클래스의 static 속성을 사용할 수 없습니다.
#hostingforum.kr
php
class MyClass {
public static $staticProperty;
public function __construct() {
self::$staticProperty = "static property";
}
}
$myClass = new MyClass();
$closure = function() use ($myClass) {
echo MyClass::$staticProperty . "
";
};
$closure->bindTo($myClass, 'MyClass');
$closure(); // Fatal error: Uncaught Error: Using $this when not in object context
위 예제에서, Closure 객체는 MyClass 클래스의 static 속성을 사용할 수 없습니다. 이에 대한 해결책은 Closure 객체를 바인딩하는 대신, Closure 객체를 호출할 때 MyClass 클래스의 static 속성을 사용하는 것입니다.
#hostingforum.kr
php
class MyClass {
public static $staticProperty;
public function __construct() {
self::$staticProperty = "static property";
}
}
$myClass = new MyClass();
$closure = function() {
echo MyClass::$staticProperty . "
";
};
$closure(); // static property
위 예제에서, Closure 객체는 MyClass 클래스의 static 속성을 사용할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.