PHP & OOP: Method visibility

This entry is part 10 of 11 in the series PHP & OOP

Class methods may be defined as public, private, or protected.

Methods declared without visibility keyword are defined as public.


class MyClass
    // Declare a public constructor
    public function __construct()

    // Declare a public method
    public function MyPublic()
        echo "I am a public function";
        echo "<br>";

    // Declare a protected method
    protected function MyProtected()
        echo "I am a protected function";
        echo "<br>";

    // Declare a private method
    private function MyPrivate()
        echo "I am a private function";
        echo "<br>";

    // This is public
    function printString()

$myclass = new MyClass;
$myclass->MyPublic(); // Works
echo "--<br>";
// $myclass->MyProtected(); Fatal Error
// $myclass->MyPrivate(); Fatal Error
$myclass->printString(); //Public, Protected and Private work


We look at these 2 statements:


-Fatal Error as MyProtected() is protected and can only be accessed by inherited class.


Fatal Error as MyPrivate() is a private function and can only be accessed in its own class.

Series Navigation<< PHP & OOP: Visibility
PHP & OOP: Magic Methods >>