Ryan Castle Ryan Castle - 1 year ago 77
PHP Question

Selecting a class using properties as a selector - PHP

So, I'm wanting to select a PHP object via its property, sorta like how you'd select an HTML element in JS through the

kinda thing.

How would I go about selecting the object of class
Which has the name of
The Night's Watch
, without knowing its variable name?


Answer Source

It is not so difficult as it would seem

// this will be array of all variables 
$vars = get_defined_vars();
foreach(array_keys($vars) as $v)
   if (gettype($$v) == 'object' and           
       get_class($$v) == 'Business'  and      // get_class returns class name
       $$v->name == 'The Night's Watch')      // test property
      echo 'Variable you find is ' . $v;  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download