...

View Full Version : How to call global function from method?



Renato Bebić
01-12-2010, 09:25 AM
Hi, I have global function WriteLog for logging and i need to use it in my class, so i imagined something like this:


class MyClass {
private $logger = null;

public function __construct($logger) {
$this->logger = $logger;
}

private function log($string) {
call_user_func($this->logger, $string);
}

public function foo() {
$this->log('Something');
}
}

$obj = new MyClass(WriteLog);

$obj->foo();


I get message:


Warning: call_user_func(WriteLog): First argument is expected to be a valid callback in...

abduraooft
01-12-2010, 09:53 AM
$obj = new MyClass(WriteLog); I think that should be

$obj = new MyClass('WriteLog');

Renato Bebić
01-12-2010, 10:03 AM
$obj = new MyClass(WriteLog); I think that should be

$obj = new MyClass('WriteLog');

Hm, I get same message. No difference at all.

Renato Bebić
01-12-2010, 10:13 AM
var_dump($this->logger);

Returns
string(8) "WriteLog" for both
new MyClass(WriteLog) and
new MyClass('WriteLog') :confused:

Renato Bebić
01-12-2010, 10:27 AM
Looks like function identifier is always string and there is no way to pass function by reference in PHP, so call_user_func only executes functions within its scope.

Any other ideas?

JAY6390
01-12-2010, 11:32 AM
Have you defined the function. This works...


class MyClass {
private $logger = null;

public function __construct($logger) {
$this->logger = $logger;
}

private function log($string) {
call_user_func($this->logger, $string);
}

public function foo() {
$this->log('Something');
}
}
function WriteLog($string) {
echo 'String: '.$string;
}

$obj = new MyClass('WriteLog');

$obj->foo();
Also you should ALWAYS encapsulate your strings in quotes. if WriteLog becomes a constant in future versions of PHP you will get a broken script

Renato Bebić
01-12-2010, 12:03 PM
Ah, i forgot to include WriteLog.php :rolleyes:

It works now :thumbsup:

JAY6390
01-12-2010, 12:11 PM
Cool! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum