PHP OOP Protected Functions


PHP OOP Protected Functions

The whole essence of this brief tutorial is to emphasize that fact that protected functions cannot be used by an unrelated class. However, they can be used by a child class. With that said, the block of code will allow you to see a public function that is displayed in another class but the protected function will not. If you changed the line of code protected function from_unrelated_protected() to public function from_unrelated_protected() you will see that the function would work and display output since it is public.

class Tag
{

    public $a;
    public $b;
    public $c;

    public function from_unrelated_class()
    {
        echo "hey public";
    }

    public function from_unrelated_public()
    {
        echo "Hey public variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }

    protected function from_unrelated_protected()
    {
        echo "Hey protected variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }


}

class Form
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->from_unrelated_public();
        return $this->myvar2;
    }

    function get_protected(){
        $this->test2 = new Tag();
        $this->myvar3 = $this->test2->from_unrelated_protected();
        return $this->myvar3;
    }


}

$test = new Form();
echo $test->myvar2;
echo $test->get_protected();


Output

OOP Protected Functions PHP

If you do change the line of code:
protected function from_unrelated_protected()
to:
public function from_unrelated_protected()
you will see that the function will display output.

Hey public variable called: testin
Hey protected variable called: testin