代码之家  ›  专栏  ›  技术社区  ›  TCCV

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

  •  0
  • TCCV  · 技术社区  · 14 年前

    在处理围绕对象传递的变量时,我一直使用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 回复  |  直到 14 年前
        1
  •  0
  •   Andreas Linden    14 年前

    另外,不赞成通过引用传递非对象,所以不要这样做。另外,所有对象都会自动通过引用传递,直到您明确地复制内存(即使用克隆)。只要使用像这样的干净结构,你就会没事了:)

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