PHP OOP私有保护

时间:2016-03-31 09:01:00

标签: php oop variables private protected

我有以下代码: 班级定义:

<?php
    class Person{
        var $name;
        public $height;
        protected $socialInsurance = "yes";
        private $pinnNumber = 12345;

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

        public function setName($newName){
            $this->name = $newName;
        }

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

        public function sayIt(){
            return $this->pinnNumber;
        }
    }

    class Employee extends Person{
    }

以及实例的部分:

<!DOCTYPE html>
<HTML>
    <HEAD>
        <META charset="UTF-8" />
        <TITLE>Public, private and protected variables</TITLE>
    </HEAD>
    <BODY>
        <?php
            require_once("classes/person.php");

            $Stefan = new Person("Stefan Mischook");

            echo("Stefan's full name: " . $Stefan->getName() . ".<BR />");

            echo("Tell me private stuff: " . $Stefan->sayIt() . "<BR />");


            $Jake = new Employee("Jake Hull");

            echo("Jake's full name: " . $Jake->getName() . ".<BR />");

            echo("Tell me private stuff: " . $Jake->sayIt() . "<BR />");

        ?>
    </BODY>
</HTML>

输出:

Stefan's full name: Stefan Mischook.
Tell me private stuff: 12345
Jake's full name: Jake Hull.
Tell me private stuff: 12345 // Here I was expecting an error

据我所知,私有变量只能从它自己的类中访问,受保护变量也可以从扩展类的类中访问。我有私有变量$pinnNumber。所以我预计,如果我拨打$Jake->sayIt(),我会收到错误消息。因为$Jake是扩展class Employee的{​​{1}}的成员。变量class Person只能从$pinnNumber访问,而不能从class Person访问。

问题出在哪里?

2 个答案:

答案 0 :(得分:4)

实际上,这不是它的工作原理。 由于您没有扩展sayIt()方法,因此没有“可访问性问题”,如果您执行了类似的操作,则会有一个:

<?php
    class Person{
        var $name;
        public $height;
        protected $socialInsurance = "yes";
        private $pinnNumber = 12345;

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

        public function setName($newName){
            $this->name = $newName;
        }

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

        public function sayIt(){
            return $this->pinnNumber;
        }
    }

    class Employee extends Person{
        public function sayIt(){
            return $this->pinnNumber;//not accessible from child class
        }
    }

答案 1 :(得分:-1)

受保护,公共和私人只是环境范围,在您的情况下,对于一个类。由于您的satIt()功能为public,因此您可以访问具有正确环境范围的功能,以访问任何privateprotected个变量。

如果您尝试这样做:

$Jake->pinnNumber

在课外,你会得到错误。

您应该在方法和类中更多地研究Scopes,然后您可以转到匿名函数;)