Bharanikumar
Bharanikumar

Reputation: 25733

what is the protected mode in php

I Protected works only one inherited class know ,

In this code , the protected works in third class ,

Is It true or any mistake i made in my code ,

<?php
class sample_visibility{

    public function my_first_public(){
        $MSG = "THIS IS MY PUBLIC FUNCTION ";
        return $MSG;
    }
    private function my_first_private(){
        $MSG = "THIS IS MY PRIVATE FUNCTION ";
        return $MSG;
    }
    protected function my_first_protected(){
        $MSG = "THIS IS MY PROTECTED FUNCTION ";
        return $MSG;
    }
}
class sample_visibilit2  extends sample_visibility{
    public function my_first_child_public(){

        $MSG = "THIS IS MY CHILD  PUBLIC FUNCTION ".$this->my_first_protected();
        return $MSG;
    }
}

class sample_visibilit3  extends sample_visibility{
    public function my_first_child_public_3(){

        $MSG = "THIS IS MY CHILD  PUBLIC FUNCTION ".$this->my_first_protected();
        return $MSG;
    }
}
$OBJ_CLASS_1 = new sample_visibility();
echo $OBJ_CLASS_1->my_first_public();

$OBJ_CLASS_3 = new sample_visibilit3();
echo $OBJ_CLASS_3->my_first_child_public_3();
?>

Upvotes: 0

Views: 235

Answers (2)

AndreKR
AndreKR

Reputation: 33678

Although your question is not very clear, your code is correct and will work.

Inside the classes sample_visibilit2 and sample_visibilit3 you can access my_first_protected(), because both classes are subclasses of sample_visibility.

Upvotes: 0

jon_darkstar
jon_darkstar

Reputation: 16768

You have made no mistake in your code. Protected elements (members or functions) are accessible by children, grandchildren, (great-)*grandchildren. Any number of inheritances is ok. They are only "protected" from unrelated classes.

public - accessible anywhere
protected - derived classes only (any number of inheritances)
private - only accessible internally

Upvotes: 3

Related Questions