How PHP calls the subclass private property in the parent class method

Source: Internet
Author: User
I want to call the private property of the subclass in the parent class, but I'm reporting a 500 error.

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;

This code runs after the server reported 500 error, why call method_exists return the result is true, still can't return the method? Thank you.

Reply content:

I want to call the private property of the subclass in the parent class, but I'm reporting a 500 error.

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;

This code runs after the server reported 500 error, why call method_exists return the result is true, still can't return the method? Thank you.

First, according to the official PHP document:

    • Public represents the global, and the inner and outer subclasses of the class can be accessed;

    • Private means that only this class can be used internally;

    • Protected is protected and is accessible only in this class or subclass or in the parent class;

Secondly, the meaning of method_exists is whether the test exists, the problem is that people really exist, but there is no authority, which is no problem.
You should use it here.protected

Private member methods seem to only invoke themselves

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.