Reputation: 257
I have a class called Converter
class Converter {
public function convert($value, $from, $to){
$this->switchUnitCall($from)($value, $to);
}
private function switchUnitCall($from){
switch($from){
case 'm':
return $this->fromM; break;
case 'km':
return $this->fromKM; break;
}
}
private function fromM($value, $to){}
private function fromKM($value, $to){}
}
I want to return the private method called fromM
or fromKM
to its caller, so I can call the fromM
with my another custom arguments inside the convert
method.
When I run the code above, I got error Undefined property: Converter::$fromM
My question, is it possible to return a method in PHP? and how is it done? Thank you.
Upvotes: 3
Views: 99
Reputation: 3757
You can return your method, but keep in mind the visibility of a specific method, and from which scope they can be called. These two methods are private and can be called only within the given class.
The problem with this code is that you have called your methods as properties, thus the error for the undefined property.
They should be called like methods with parentheses and 2 mandatory passed $this->fromM($value, $to)
, also you need to pass the arguments $value
and $to
to switchUnitCall()
since they are mandatory too.
Also, these two methods need to return a result:
class Converter {
public function convert($value, $from, $to){
$this->switchUnitCall($from, $value, $to);
}
private function switchUnitCall($from, $value, $to){
switch($from){
case 'm':
return $this->fromM($value, $to);
break;
case 'km':
return $this->fromKM($value, $to);
break;
}
}
private function fromM($value, $to){
//return conversion
}
private function fromKM($value, $to){
//return conversion
}
}
Upvotes: 1
Reputation: 2218
You can't return method but you can use method name to invoke it dynamically:
class Converter {
public function convert($value, $from, $to){
$method=$this->switchUnitCall($from);
$this->$method($value, $to);
}
private function switchUnitCall($from){
switch($from){
case 'm':
return "fromM"; break;
case 'km':
return "fromKM"; break;
}
}
private function fromM($value, $to){}
private function fromKM($value, $to){}
}
Upvotes: 3