سؤال

This is probably a basic question but im following this tutorial and at one point the code looks something like this.

<?php

class person
{
    public $name;
    public $height;
    protected $social_security_no;
    private $pin_number = 3242;

    public function __construct($person_name)
    {
        $this->name = $person_name;
    }
    public function set_name($new_name)
    {
        $this->name = $new_name;
    }

    protected function get_name()
    {
        return $this->name;
    }

    public function get_pin_number_public()
    {
        $this->pub_pin = $this->get_pin_number();
        return $this->pub_pin;
    }

    private function get_pin_number()
    {
        return $this->pin_number;
    }

}

class employee extends person
{

    public function __construct($person_name)
    {
        $this->name = $person_name;
    }

    protected function get_name()
    {
        return $this->name;
    }
}

However when i use this

<?php include "class_lib.php";?>
    </head>
    <body id="theBody">
    <div>

<?php
$maria = new person("Default");

$dave = new employee("David Knowler");
echo $dave->get_name();
?>

i get this error

Fatal error: Call to protected method employee::get_name() from context '' in C:\Users\danny\Documents\Workspace\test\index.php on line 13

The problem seems to be when i add protected to the get_name() function in the employee class but it seems to me that this is the preferred way to override in the tutorial. Any ideas?

هل كانت مفيدة؟

المحلول 2

"The problem seems to be when i add protected to the get_name() function in the employee class" -- this is your answer. A protected method can only be called from the very same class or subclasses, not "from the outside". Your method has to be public if you want to use it this way.

نصائح أخرى

The problem isn't that you cannot override the protected method, it's that you are calling a protected method from outside of the class.

After the class is instantiated, you can call a public method which in turn could call get_name() and you will see that the code will work as expected.

For example:

class employee extends person {

    function __construct($person_name){
        $this->name = $person_name;
    }

    protected function get_name() {
        return $this->name;
    }

    public function name()
    {
        return $this->get_name();
    }
}

$dave = new employee("David Knowler");
echo $dave->name();

In your example, you would probably be best making get_name() public.

You can access get_name() within person class or employee class not outside of these two classes.

check protected visibility

http://php.net/manual/en/language.oop5.visibility.php

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top