tags:

views:

33

answers:

1

Which is the most semantically "correct" way to get/set variables when using OO PHP?

From what I know, there are getters/setters, passing by reference and passing by value. Passing by value is slower than passing by reference, but passing by reference actually manipulates the memory of your variable. Assuming I would like to do this (or wouldn't mind at least), which is more semantically correct/more efficient?

I've been using the getter/setter type when dealing with variables that are passed around the object. I find this to be semantically correct and easier to "read" (no long list function arguments). But I think it's less efficient.

Consider this example (of course it's contrived):

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

the most efficient way is if you do not use private/protected but public members, you accees those public members from outside like $instance->member

also it's deprecated to pass non-objects by reference so just don't do it. also are all objects automatically passed by reference until you explcitly copy the memory ie. by using clone. just use a clean structure like this one and youÄll be fine :)

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;
    }
}
zolex
interesting, I didn't realize that passing non-objects by reference was deprecated.
Tim