簡體   English   中英

獲取變量/成員的最有效方法

[英]most efficient way to getting variables/members

使用OO PHP時,最語義上最正確的方式來獲取/設置變量?

據我所知,有吸氣劑/阻氣劑,通過參考傳遞和通過價值傳遞。 按值傳遞比按引用傳遞要慢,但是按引用傳遞實際上會操縱變量的內存。 假設我想這樣做(或至少不會介意),這在語義上更正確/更有效?

在處理圍繞對象傳遞的變量時,我一直在使用getter / setter類型。 我發現這在語義上是正確的,並且更容易“閱讀”(沒有長列表函數參數)。 但我認為效率較低。

考慮以下示例(當然是人為設計的):

class bogus{
    var $member;

    __construct(){   
        $foo = "bar"
        $this->member = $foo;
        $this->byGetter();
        $this->byReference($foo);
        $this->byValue($foo);
    }

    function byGetter();{
        $baz =& $this->member; 
        //set the object property into a local scope variable for speed
        //do calculations with the value of $baz (which is the same as $member)
        return 1;
    }

    function byReference(&$baz){
        //$baz is already set as local.  
        //It would be the same as setting a property and then referencing it
        //do calculations with the value of $baz (same as $this->member)
        return 1;
    }

    function byValue($baz){
        //$baz is already set as local.  
        //It would be the same as setting a property and then assigning it
        //do calculations with the value of $baz 
        return 1;
    }
}

最有效的方法是,如果您不使用私有/受保護的而是公共成員,則可以從外部訪問那些公共成員,例如$ instance-> member

還建議不要通過引用傳遞非對象,所以不要這樣做。 也是所有對象自動通過引用傳遞,直到您明確地復制內存即。 通過使用克隆。 只要使用像這樣的干凈結構,就可以了:)

class Example_SetterGetter
{
    /**
     * @var stdClass
     */
    protected $_myObj;

    /**
     * A public constructor
     * 
     */
    public function __construct(stdClass $myObj = null)
    {
        if ($myObj !== null)
        {
            $this->setMyObj($myObj);
        }
    }

    /**
     * Setter for my object
     * @param stdClass $var
     * @return Example_SetterGetter
     */
    public function setMyObj(stdClass $var)
    {
        $this->_myObj = $var;
        return $this;
    }

    /**
     * Getter for my object
     * @return object
     */
    public function getMyObj()
    {
        return $this->_myObj;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM