Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Private Function From Outside Class

Tags:

oop

php

private

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

like image 571
Mob Avatar asked May 13 '26 10:05

Mob


1 Answers

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.

like image 197
CodeCaster Avatar answered May 16 '26 00:05

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!