Jump to content

Order of precedent for accessing properties and ternary operators


Recommended Posts

$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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.