PHP Script: Call Method Dynamically. Below is PHP Script which describes the full process:
<?php
$fnc = "canCall";
if (!is_callable($fnc)) {
echo "Cant call method: $fnc <BR>";
} else {
echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}
$fnc = "canCall2";
if (!is_callable($fnc)) {
echo "Cant call method: $fnc <BR>";
} else {
echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}
function canCall($a = 10)
{
return $a * 5;
}
$caller_class = new CallerClass();
$caller_class->check();
class CallerClass
{
private $for_method1 = 10;
public function check()
{
$fnc = "method1";
if (!is_callable(array(&$this, $fnc))) {
echo "$fnc is not callable function";
} else {
$this->{"for_method1"} = 20;
echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
}
$fnc = "method2";
if (!is_callable(array(&$this, $fnc))) {
echo "$fnc is not callable function";
} else {
echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
}
}
public function method1()
{
return "From method 1 <$this->for_method1>";
}
}
?>
Which will output as below:
Return from method canCall: 75
Cant call method: canCall2
Return from method1:From method 1 <20>
method2 is not callable function
<?php
$fnc = "canCall";
if (!is_callable($fnc)) {
echo "Cant call method: $fnc <BR>";
} else {
echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}
$fnc = "canCall2";
if (!is_callable($fnc)) {
echo "Cant call method: $fnc <BR>";
} else {
echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}
function canCall($a = 10)
{
return $a * 5;
}
$caller_class = new CallerClass();
$caller_class->check();
class CallerClass
{
private $for_method1 = 10;
public function check()
{
$fnc = "method1";
if (!is_callable(array(&$this, $fnc))) {
echo "$fnc is not callable function";
} else {
$this->{"for_method1"} = 20;
echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
}
$fnc = "method2";
if (!is_callable(array(&$this, $fnc))) {
echo "$fnc is not callable function";
} else {
echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
}
}
public function method1()
{
return "From method 1 <$this->for_method1>";
}
}
?>
Which will output as below:
Return from method canCall: 75
Cant call method: canCall2
Return from method1:From method 1 <20>
method2 is not callable function
No comments:
Post a Comment