-
-
Save rdohms/892220 to your computer and use it in GitHub Desktop.
<?php | |
//Original code | |
$this->setProperty( $data['property'] ); | |
//How it has to be done because array may not contain that value (its optional) | |
$this->setProperty( isset($data['property'])? $data['property'] : null ); | |
/* | |
* Question is: Is there a cleaner way of doing this, if so, how? | |
* | |
* Second question, is: would the code below (create a native php function) make sense as a good solution? | |
*/ | |
$this->setProperty( array_read('property', $data ); | |
// In this case the C code behind this would check for presence of the key and return null if not present | |
// Another solution is to create a SPL function in PHP format to do this | |
//Thanks |
In my tests the ternary operator still raised a PHP Notice as its still trying to read an unexisting key in the array. I wish it did "isset" internally and suppressed that.
Rdohms Hello!
I think creating a native function to perform this task could "clean up " your code, but difficult reading software.
To me, your solution seems to be the cleanest. I would not use another. :)
$ this-> setProperty (isset ($ data ['property'])? $ data ['property']: null);
Maybe something like:
$this->setProperty(array_shift((array_slice($data, ($i = array_search('property', array_keys($data))) && !!$i ? $i : count($data), 1))));
There was an PHP RFC for a new operator called "issetor" that does exactly that. Can't show you that 'cause PHP Wiki is on maintenance, but it was something like this:
$this->setProperty( issetor($data['property'], null) );
I think the second parameters default value was false instead of null. Anyway, that operator was rejected. I always use:
$this->setProperty(isset($ data ['property'])? $data['property'] : null);
Patch in the works.
Thanks @davidcoallier
Having the ternary operator execute a "isset" internally would be a great addition to the language, looking forward to it.
btw @alganet .. that has to be the ugliest operator name in the history of programming... :D
@rdohms agreed
Why don't you do:
$this->setProperty($data['property'] ?: null);