Search code examples
phpoopprivate

Accessing Private Function From Outside Class


I'm learning OO stuff, and came across this:

class n{

    private function f($v){
        return $v*7;
    }

    function c(){
       return $this->f(5);
    }
}

$o = new n;
echo $o->c(); //returns 35

Doesn't that beat the purpose of declaring functions private if I can access it still from outside the class? Shouldn't this be blocked altogether? Am I missing something? Please help clear up. Thanks


Solution

  • Public functions are meant to perform operations on an instance of that class. Say, Save().

    The internal workings of Save() are not interesting for the caller; he simply wants to save it and doesn't care how that happens.

    As a matter of style, you might or might not want to actually perform the saving in that method. It might depend on design choices, or on properties of the object. See:

    class FooObject
    {
    
        private $_source;
    
        public function Save()
        {
    
            if ($this->_source == "textfile")
            {
                $this->saveToTextfile();
            }
            elseif ($this->_source == "database")
            {
                $this->saveToDatabase();
            }
        }
    
        private function saveToTextfile()
        {
            // Magic
        }
    
        private function saveToDatabase()
        {
            // Magic
        }
    }
    

    You don't want anyone to call the private methods directly, because they are for internal use only. However, a public method may indirectly call a private method.