Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无法访问私有属性_Php - Fatal编程技术网

Php 无法访问私有属性

Php 无法访问私有属性,php,Php,我对以下代码有问题,我正在尝试打印学生的数据,但出现以下错误: 致命错误:未捕获错误:无法访问私有属性 秘书::$学生 如果我将属性设置为public,则它可以正常工作 class Student { private $name; public function __construct($name){ $this->name = $name; } public function getName(){ return $th

我对以下代码有问题,我正在尝试打印学生的数据,但出现以下错误:

致命错误:未捕获错误:无法访问私有属性 秘书::$学生

如果我将属性设置为public,则它可以正常工作

class Student {

    private $name;

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

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

}

class Secretary{

    private $students = array();

     public function printStudents(){

         foreach($this->students as $key=>$value){
             echo $value->name . " ";
         }
     }

}

$secretary = new Secretary();

// Add students.
$student = new student("Student1");
array_push($secretary->students,$student);

$secretary->printStudents();

学生->姓名是私有数据成员。这意味着,根据定义,您不能在Student定义之外访问它。这基本上就是getName的用途,因此您可以在定义之外访问它

您要做的是:

foreach($this->students as $key=>$value){
    echo $value->getName() . " ";
}
这将如预期的那样发挥作用


如果您想了解有关访问修饰符的更多信息,可以阅读它们。

您不能访问超出其自身范围的类的私有属性。为了达到你想要的,考虑一种新的方法,比如:< /P>
public function addStudent(Student $s): Secretary
{
    array_push($this->students, $s);
    return $this;
}
然后,你可以把你的新学生附加到秘书的职位上

$s = new Secretary();
$s->addStudent(new Student('Foo'));

$s->printStudents();

您可以看到它的一部分正在工作。

您需要一个setter函数。不能直接访问私有变量

在班级秘书中,您需要一个函数AddStudentStudent$students

此函数将类似于:

public function AddStudent(Student $student) {
    if (!$this->students->contains($student)) {
        $this->students[] = $student;
    }
    return $this;
}

之后,您可以使用函数“printStudents”打印出所有学生。

您正在尝试访问班级以外的私人班级成员。你预计会发生什么?把它公之于众或者把这个逻辑转移到这个类中;你可以向Secretary添加另一个方法来添加学生。如果你不想在类外使用getName来获取名称,为什么要使用getName?这应该可以回答您的姓名问题,可能是重复的