View Full Version : Calling a function/constructing a class from an object's property

06-30-2010, 12:01 AM
Is it even possible to do this?
So normally you can do:
$var = 'substr';
echo $var('My String', 1); // 'y String'

But I can't seem to do:
$var->method = 'substr';
echo $var->method( 'My String', 1 );

How can I make it work?

06-30-2010, 05:45 AM

07-01-2010, 08:46 AM
Well I do know of that but is there another way instead of assigning it to another variable?

07-01-2010, 03:15 PM

07-01-2010, 03:30 PM
Take a look at the PHP __call() method. A Google search will give you a lot of results, but I found this one (http://www.garfieldtech.com/blog/php-magic-call) to be the most concise and relevant to your question.

07-01-2010, 05:10 PM
No, call is an overload to invoke non-public or chained methods. Calling a function that is pointed to by a member needs call_user_func[_array], ReflectionFunction / ReflectionMethod (the latter inherits from former, so just ReflectionFunction is fine), or __invoke on the callback through a closure. Note the link you posted uses the call_user_func[_array] route.

07-01-2010, 05:39 PM
The only reason I pointed the OP in the direction of using a temporary variable name is because from what I've experienced in the past (haven't tested this in a while though) call_user_func[_array] isn't very efficient.

// Straight-up call, fast as !@#$%
$text = substr( $text, 0, 10 );

// Not as fast but not at all slow
$var->method = 'substr';
$func_name = $var->method;
$text = $func_name( $text, 0, 10 );

// Bit of a hog
$var->method = 'substr';
$text = call_user_func( $var->method, $text, 0, 10 );

Fou-Lu also brought up Reflection, which is a very reliable option though I have never taken the time to benchmark it versus the call_user_func[_array] solution.

07-01-2010, 06:23 PM
Thats true yes, assumably variable functions are compile or link time evaluated.
I benchmarked the reflections a few years ago, pretty sure I did the inokes as well. 5.0.x was slow if I recall, 5.2.x was fast, and I think it beat all. I did a closure with 5.3.0, and I recall Closure was ftw.