Can PHP dissect its own syntax?
Posted
by Nathan Long
on Stack Overflow
See other posts from Stack Overflow
or by Nathan Long
Published on 2010-05-03T14:40:35Z
Indexed on
2010/05/03
14:48 UTC
Read the original article
Hit count: 328
php
Can PHP dissect its own syntax? For example, I'd like to write a function that takes in an input like $object->attribute
and says to itself:
OK, he's giving me
$foo->bar
, which means he must think that$foo
is an object that has a property calledbar
. Before I try accessingbar
and potentially get a 'Trying to get property of non-object' error, let me check whether$foo
is even an object.
The end goal is to echo a value if it is set, and fail silently if not.
I want to avoid repetition like this:
<input value="<? if(is_object($foo) && is_set($foo->bar)){ echo $foo->bar; }?> "/>
...and to avoid writing a function that does the above, but has to have the object and attribute passed in separately, like this:
<input value="<? echoAttribute($foo,'bar') ?>" />
...but to instead write something which:
- preserves the object->attribute syntax
- 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 this all depends on PHP being able to tell me "what kind of thing am I asking for when I say $object->attribute
or $array[$key]
", so that my function can handle each according to its own type.
Is this possible?
© Stack Overflow or respective owner