Jump to content

Order of precedent for accessing properties and ternary operators


Go to solution Solved by requinix,

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;
    }
Edited by NotionCommotion

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

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
  • Solution

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.