【问题标题】:most efficient way to getting variables/members获取变量/成员的最有效方法
【发布时间】:2010-09-24 21:30:13
【问题描述】:

在使用 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;
    }
}

【问题讨论】:

  • 这有什么实际用途吗?给它一个基准,看看是否有显着差异。如果没有,请保持简单(且可读)。
  • 好吧,这只是一个例子来说明我在说什么。例如,我知道编写一个带有 8 个通过引用传递的参数的函数会更快,但它非常难看。相反,如果我使用对象属性将变量从一件事传递到另一件事,那么它会更干净,但速度更慢。那么在语义上哪个更可取?

标签: php semantics


【解决方案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;
    }
}

【讨论】:

  • 有趣,我没有意识到通过引用传递非对象已被弃用。
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 2016-07-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多