
GearmanClient::echo 함수는 작업을 제출하고 결과를 바로 받는 함수로, 작업을 제출할 때는 작업의 결과를 받기 위해 callback 함수를 등록해야 합니다.
callback 함수를 등록하는 코드는 다음과 같습니다.
#hostingforum.kr
php
$client = new GearmanClient();
$client->addServer('localhost', 4730);
$client->setClientWorkload(1000);
$client->addTask('echo', 'Hello, world!', $this, 'taskComplete');
여기서 `$this->taskComplete`가 callback 함수입니다. `$this`는 현재 객체를 의미합니다.
하지만 `$this`를 사용하는 코드는 다음과 같이 객체를 생성하기 전에 사용하는 경우도 있습니다.
#hostingforum.kr
php
$client = new GearmanClient();
$client->addServer('localhost', 4730);
$client->setClientWorkload(1000);
$obj = new TestClass();
$client->addTask('echo', 'Hello, world!', $obj, 'taskComplete');
여기서 `$obj`는 TestClass라는 클래스의 객체입니다.
callback 함수를 등록할 때 `$this`를 사용할 수 없나요?
아니요, `$this`를 사용할 수 있습니다. `$this`는 현재 객체를 의미하므로, callback 함수가 호출될 때 `$this`는 이미 생성되어 있는 객체를 가리킵니다.
그런데 `$this`를 사용할 때는 `$this`가 이미 생성되어 있어야 한다는 것입니다.
이 말은 `$this`를 사용하는 코드는 객체를 생성하기 전에 사용할 수 없다는 것을 의미합니다.
예를 들어, 다음과 같이 코드를 작성할 수 없습니다.
#hostingforum.kr
php
$client = new GearmanClient();
$client->addServer('localhost', 4730);
$client->setClientWorkload(1000);
$client->addTask('echo', 'Hello, world!', $this, 'taskComplete');
$obj = new TestClass();
이 코드는 `$this`를 사용하기 전에 객체를 생성하기 때문에 오류가 발생합니다.
callback 함수를 등록할 때 `$this`를 사용할 수 없는 경우에는 어떻게 해야 하나요?
이 경우는 `$this`를 사용하지 않고, callback 함수를 등록할 수 있습니다. 예를 들어, 다음과 같이 코드를 작성할 수 있습니다.
#hostingforum.kr
php
$client = new GearmanClient();
$client->addServer('localhost', 4730);
$client->setClientWorkload(1000);
$obj = new TestClass();
$client->addTask('echo', 'Hello, world!', array($obj, 'taskComplete'));
이 코드는 `$this`를 사용하지 않고, callback 함수를 등록할 수 있습니다.
또는, 다음과 같이 코드를 작성할 수 있습니다.
#hostingforum.kr
php
$client = new GearmanClient();
$client->addServer('localhost', 4730);
$client->setClientWorkload(1000);
$obj = new TestClass();
$client->addTask('echo', 'Hello, world!', function() use ($obj) {
$obj->taskComplete();
});
이 코드는 `$this`를 사용하지 않고, callback 함수를 등록할 수 있습니다.
결과적으로, callback 함수를 등록할 때 `$this`를 사용할 수 없나요?
아니요, `$this`를 사용할 수 있습니다. `$this`는 현재 객체를 의미하므로, callback 함수가 호출될 때 `$this`는 이미 생성되어 있는 객체를 가리킵니다.
2025-04-20 08:02