Can PHP parse native syntax? For example, I would like to write a function that takes an input, such as $object->attribute , and tells itself:
OK, he gives me $foo->bar , which means that he should think that $foo is an object that has the bar property. Before trying to access bar and potentially get the message “Trying to get a non-object property”, let me check if $foo even an object.
The ultimate goal is to echo the value if it is set, and fails if not .
I want to avoid repeating as follows:
<input value="<? if(is_object($foo) && is_set($foo->bar)){ echo $foo->bar; }?> "/>
... and to avoid writing a function that does the above, but must have an object and attribute passed separately, for example:
<input value="<? echoAttribute($foo,'bar') ?>" />
... but instead write something that:
- saves the syntax of the attribute object->
- is flexible: can also handle array keys or regular variables
Like this:
<input value="<? echoIfSet($foo->bar); ?> /> <input value="<? echoIfSet($baz['buzz']); ?> /> <input value="<? echoIfSet($moo); ?> />
But it all depends on how PHP can tell me "what I ask when I say $object->attribute or $array[$key] ", so that my function can handle each in its own type.
Is it possible?
Update
Here I got some good answers and experimented a bit. I wanted to take stock.
- The answer to my original question seems to be no, but we found a way to do this, I tried to do it. Techpriester pointed out that I can pass the string '$ foo-> bar' to the function and parse it and
eval() . Not the approach I want to take, but deserves a mention. - Peter Bailey noted that something like
$foo->bar is evaluated before passing the function. I should have thought about it, but for some reason I didn’t. Thanks Peter! - Will Vousden showed that passing
$foo->$bar by reference allows the function to evaluate it, rather than evaluate it in advance. Its function shows that isset($foo->bar) will not complain if $foo not an object that I did not know about.
More interestingly, his example seems to imply that PHP is waiting to evaluate a variable until it is absolutely required.
If you pass something by value , then of course PHP must define the value . Like this:
$foo->bar = 'hi'; somefunction($foo->bar);
But if you pass by reference , it can wait to determine the value when it is really needed.
Like this (following the order in which events occur):
echo ifSet($foo->bar);
Thanks to all who responded! If I distorted something, let me know.