PHP OOP 私有保护

PHP OOP private protected

我有以下代码: Class定义:

<?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

据我所知,私有变量只能从它自己的 class 访问,而受保护变量也可以从扩展 class 的 class 访问。我有私有变量 $pinnNumber。所以我预计,如果我调用 $Jake->sayIt(),我会得到一个错误。因为 $Jake 是扩展 class Personclass Employee 的成员。并且变量 $pinnNumber 应该只能从 class Person 访问,而不是从 class Employee.

问题出在哪里?

Protected、public 和 private 只是环境范围,在您的情况下,是 Class。由于您的 satIt() 函数是 public,您可以访问具有正确环境范围的函数以访问任何 privateprotected 变量。

如果您尝试这样做:

$Jake->pinnNumber

在 Class 之外,就会出现错误。

您应该更多地研究方法和 Classes 中的作用域,然后您可以转向匿名函数 ;)

实际上,事情并非如此。 因为你没有扩展 sayIt() 方法,所以没有 "accessibility problem",如果你这样做的话,会有一个:

<?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
        }
    }