NotionCommotion Posted May 8, 2017 Share Posted May 8, 2017 $obj?$obj:$this->{$prop} is not correct. My desire is to return $obj->{$prop} if $obj is set, otherwise $this->{$prop}. How should it be written? PS. I probably should just pass $this to the method if I really want properties from $this, but still would like to know how to do what I was attempting. protected function getObjProps(array $props, $obj=null) { //Return given properties of either a provided object or the $this object $o=new \stdClass; foreach($props as $prop){ $o->{$prop}= property_exists($obj?$obj:$this, $prop) ?($obj?$obj:$this->{$prop}) :null; } return $o; } Link to comment Share on other sites More sharing options...
requinix Posted May 8, 2017 Share Posted May 8, 2017 Nested ternaries generally means you need to refactor. protected function getObjProps(array $props, $obj=null) { //Return given properties of either a provided object or the $this object $o = new \stdClass; $source = ($obj ?: $this); foreach ($props as $prop) { $o->{$prop} = (property_exists($source, $prop) ? $source->$prop : null); // or unless $obj and $this are too magical, simply //$o->{$prop} = $source->$prop; } return $o; }Anyway, the syntax you're looking for is ($obj ? $obj : $this)->$prop Link to comment Share on other sites More sharing options...
NotionCommotion Posted May 8, 2017 Author Share Posted May 8, 2017 I had already tried doing so, but received an error. Note that I am not yet using php7. Also, thanks for the $source = ($obj ?: $this); code. I hadn't known it was possible. I take it is is just shorthand for $source = ($obj ?: $this);, right? http://php.net/manual/en/language.operators.comparison.php doesn't do a good job documenting it. <?php $o1 = new \stdClass; $o2 = new \stdClass; $o1->bla=123; $prop='bla'; $x=($o1 ? $o1 : $o2)->$prop; Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in /var/www/public/noname2.php on line 7 Link to comment Share on other sites More sharing options...
requinix Posted May 8, 2017 Share Posted May 8, 2017 Yeah, PHP 7 has a number of syntax improvements. You'll have to use the long form. And yes, $x ?: $y is shorthand for $x ? $x : $y. PHP 7 also adds $x ?? $y which is short for isset($x) ? $x : $y. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.