Home > Backend Development > PHP Tutorial > How to call subclass private attribute in parent class method in PHP

How to call subclass private attribute in parent class method in PHP

WBOY
Release: 2016-07-06 13:54:16
Original
1740 people have browsed it

I want to call the private attribute of the subclass in the parent class, but a 500 error is reported.

<code>class A
{
    public function __get($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter))
        {
            return $this->$getter();
        }
    }
}

class B extends A
{
    private function getname()
    {
        return 'karly';
    }
}

$b = new B();
echo $b->name;</code>
Copy after login
Copy after login

After this code is run, the server reports a 500 error. Why does calling method_exists return true, but the method cannot be returned? Thanks.

Reply content:

I want to call the private attribute of the subclass in the parent class, but a 500 error is reported.

<code>class A
{
    public function __get($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter))
        {
            return $this->$getter();
        }
    }
}

class B extends A
{
    private function getname()
    {
        return 'karly';
    }
}

$b = new B();
echo $b->name;</code>
Copy after login
Copy after login

After this code is run, the server reports a 500 error. Why does calling method_exists return true, but the method cannot be returned? Thanks.

First follow the official php documentation:

  • public means global and can be accessed by subclasses inside and outside the class;

  • private means private and can only be used within this class;

  • protected means protected and can only be accessed in this class or subclass or parent class;

Secondly, the meaning of method_exists is to test whether it exists. The problem is that it really exists, but it just doesn’t have permission. This is not a problem.
In summary, you should use protected

It seems that private member methods can only be called by themselves

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template