note 105937 deleted from function.in-array by sobak

From: Date: Sat, 25 Feb 2017 06:04:51 +0000
Subject: note 105937 deleted from function.in-array by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208842@lists.php.net to get a copy of this message
Note Submitter: chris at axxis dot gr ---- It's funny how PHP has an in_array method, but not an in_object one. Here is a simple function which will check if a value can be found within an object. <?php // in_object method // to check if a value in an object exists. function in_object($value,$object) { if (is_object($object)) { foreach($object as $key => $item) { if ($value==$item) return $key; } } return false; } ?> This is very useful if an object has been created dynamically (especially from external code, which you don't control, as in an application-plugin, CMS, etc), and you don't know the object's properties. The above function will return the property, so you will be able to use it in your code later on. Here is a very good basic example of how useful this function is! <?php class My_Class { function __construct($key, $value) { $this->$key = $value; // As you can see, this is a dynamic class, its properties and values can be unknown... } } function in_object($value,$object) { if (is_object($object)) { foreach($object as $key => $item) { if ($value==$item) return $key; } } return false; } function manipulate_property($value,$object) { if ($property = in_object($value,$object)) { // value found. I can now use this property. // I can simply echo'it (makes no sense, as I could instead simply echo "value") echo "<br />I found the property holding this value: ".$object->$property; // or (here comes the good part) // change the property $object->$property = "This is a changed value!"; echo "<br />I changed the value to: ".$object->$property; // or return it for use in my program flow return $property; } else { echo "Value NOT FOUND!<br />"; return false; } } // imagine if some function creates the class conditionally... if ( 1 == 1) { $class = new My_Class("property","Unchanged Value"); } else { $class = new My_Class("property","Some Other Value"); } // now let's check if the value we want exists, and if yes, let's have some fun with it... $property = manipulate_property("Unchanged Value",$class); if ($property) { $my_variable = $class->$property; echo "<br />This is my variable now:".$my_variable; } else $my_variable = $some_other_variable; ?> Just run it to see for yourself!

« previous php.notes (#208842) next »