Okay, i have little MVC what works like
somesite/classname/classfunction/function
class test(){
public function test2(){
// action will be 'function' in adress
$action = $this->action ? $this->action : array($this, 'test3');
function test3(){
print 1;
}
$action();
}
}
So, if we run somesite/test/test2/test3 it will print '1', but if we run somesite/test/test2/phpinfo it will show phpinfo.
Question: how to check existing of function in class function ?
UPD
Don't forget about phpinfo, function_exists will show it.
method_exists search in class functions, but not in functions of class function
UPD Solution
class test{
public function test2(){
// site/test/test2/test3
$tmpAction = $this->parenter->actions[1]; // test3
$test3 = function(){
print 1;
};
if(isset($$tmpAction)){
$$tmpAction();
}else{
$this->someDafaultFunc();
}
}
}
3 Answers 3
http://php.net/function-exists
if ( function_exists('function_name') ) {
// do something
}
if ( method_exists($obj, 'method_name') ) { /* */ }
You should also check out the magic method __call()
Comments
To check whether a certain method in a class exists, use: http://php.net/method-exists
$c = new SomeClass();
if (method_exists($c, "someMethod")) {
$c->someMethod();
}
You are also allowed to use the class name:
if (method_exists("SomeClass", "someMethod")) {
$c = new SomeClass();
$c->someMethod();
}
To "fix" your problem, make test3() a class method:
class test(){
private function test3() {
print 1;
}
public function test2(){
// action will be 'function' in adress
$action = $this->action ? $this->action : array($this, 'test3');
if (method_exists($this, $action)) {
$this->$action();
} else {
echo "Hey, you cannot call that!";
}
}
}
5 Comments
private ?class test{
public function test2(){
// site/test/test2/test3
$tmpAction = $this->parenter->actions[1]; // test3
$test3 = function(){
print 1;
};
if(isset($$tmpAction)){
$$tmpAction();
}else{
$this->someDafaultFunc();
}
}
}
METHODS. So, inside the class, simply -if (method_exists($this, 'methodName'))test3insidetest2cannot be invoked usingarray($this, 'test3'). You should avoid functions within functions. Hoping it's just a bad copy-n-paste example.functiondeclarations inside another function.phpinfoout. Still, I'd usemethod_existsand maketest3a class method to make it clean OOP.