获得变量/成员的最有效方法

时间:2010-09-24 21:30:14

标签: php semantics

使用OO PHP时,获取/设置变量的语义最“正确”的方法是什么?

据我所知,有getter / setter,通过引用传递和传递值。传递值比传递引用要慢,但是通过引用传递实际上会操纵变量的内存。假设我想这样做(或者至少不介意),这在语义上更正确/效率更高?

在处理围绕对象传递的变量时,我一直在使用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;
    }
}

1 个答案:

答案 0 :(得分:0)

最有效的方法是,如果您不使用私人/受保护但是公共成员,您可以加入来自外部的公共成员,例如$ instance-> member

也不推荐通过引用传递非对象,所以不要这样做。也是所有通过引用自动传递的对象,直到你explcitly复制内存,即。通过使用克隆。只需使用像这样的干净结构你就可以了:)

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;
    }
}