I need to call an function that is part of an object. The following call works as one would expect:
$someobject = getobject();
$result = $someobject->somefunction->value();
However, I need the “somefunction” component to be a variable.
I have tried to do it like this:
$var = 'somefunction';
$result = '$someobject->' . $var '->value'();
This does not work, but I hope it conveys what I am looking for. I’ve also tried a lot of variations based upon call_user_func()
– without finding a syntax that works.
I am running: PHP 7.2.24-0ubuntu0.18.04.3. Vanilla version for Ubuntu 18.04 LTS.
3
Answers
Hooray!
The following (two alternative valid syntaxes are produced for the second line) works as expected without producing any errors:
The following:
also works (i.e. it produces the expected result), but it also produces this warning:
Many thanks to all that commented. In particular Duc Nguyen and Swetank Poddar. I think it was the comment by Duc Nguyen in combination with the following comment by Swetank Poddar that finally cracked it.
To access a property or method dynamically based on its name, you simply use one more
$
sign than you would normally.For example, if we have this object:
Then we can access the property normally:
Or dynamically by name:
Similarly, we can access the method normally:
Or dynamically by name:
Note that your example is a bit confusing, because you talk about “accessing a function where one part is a variable”, but all you’re actually trying to do is access a property dynamically, and you then happen to be calling a method on the object stored in that property. So the part you’ve called
somefunction
is actually the name of a property.Here’s an example that looks a bit like yours, but with the names changed: