Fatal error: cannot access protected property

Views: 48 Last modified: July 31st, 2011 Comments: 0

While you are playing around with the OOP possibility’s in PHP, you might run into a fatal error like this (with another path off course):

Fatal error: Cannot access protected property protected_prop::$propertie in C:\server\htdocs\tests\class.php on line 7

In this case, it means you try to access a “protected” declared property. This means that the particular property (declared as protected) only accessible is within the class itself and by inherited or parent classes. So you cannot access it from outside the class.

The above mentioned fatal error is caused by the following code

<?php
class protected_prop{
    // Note the keyword protected
    protected $propertie = 'This is a protected propertie';

    // note the ketword public
    public function GetProtected(){
        return $this->propertie;
    }
}

// Create instance
$instance = new protected_prop();
    // Will result in fatal error
    echo $instance->propertie;

?>

However, when we want that specific property, depending on your code, you might have several solutions. We go through 2 easy solutions.

First of all, you might declare the property by prefixes it with “public” or “var” (which has the same result) , like this (This property is now accessible from everywhere):

<?php
class protected_prop{
    // Note the keyword public
    public $propertie = 'I am not a protected property anymore!';

    // note the keyword public
    public function GetProtected(){
        return $this->propertie;
    }
}

// Create instance
$instance = new protected_prop();
    // Will output: I am not a protected property anymore!
    echo $instance->propertie;

?>

Or you want it to stay protected and you could create a simple method which returns the value of the specified property.

<?php
class protected_prop{
    // Note the keyword protected
    protected $propertie = 'I am a protected property!';

    // note the keyword public (leaving public out would have the same result))
    public function GetProtected(){
        // return the protected property
        return $this->propertie;
    }
}

// Create instance
$instance = new protected_prop();
    // Will result in: I am a protected property!
    echo $instance->GetProtected();

?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)
    Bluehost

    Mail this!

    To: From:Sum {3+9} =  
    Anything to add ?

        You must be logged in to post a comment.