Ryan Castle Ryan Castle - 6 months ago 8
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

$('.element[selector=false]')
kinda thing.

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

Thanks!

Answer

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;  
Comments