0

有人可以解释一下为什么当我这样做时print_r($student->getStudents())我只得到数组的大小并is_array返回false。

这是我的输出

Jane Doe enrolled at Aviation High School
All students:
Nope!3

<?php
 class Student{
 public $name;
 public $students = array('Jason', 'Joe');
 public function __construct($name){
     $this->name = $name;
     $this->students = array_push($this->students, $name);
 }
 public function lastName(){
    return "Doe";
 }

 public function getStudents(){
    return $this->students;
 }
}

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

class Admin{
 public function enroll(Student $student,School $school){
     echo $student->name.' '.$student->lastName().' enrolled at '. $school->name;
     echo '<br />All students:<br />';
     echo is_array($student->getStudents()) ? 'Yeah!':'Nope!' ;
 }
}

$student = new Student("Jane");
$school = new School("Aviation High School");

$admin = new Admin();
$admin->enroll($student, $school);
4

3 回答 3

5

因为当您array_push使用数组的长度时,您正在覆盖数组。

http://us2.php.net/manual/en/function.array-push.php

改变:

$this->students = array_push($this->students, $name);

到:

array_push($this->students, $name);

或者只是这样做:

$this->students[] = $name;
于 2013-05-15T17:56:15.073 回答
4

array_push不返回新数组,它直接修改你传递给它的数组并返回数组的新长度。

因此,调用后$this->students = array_push($this->students,$name)你有3作为值,这显然不是一个数组。

文档

于 2013-05-15T17:56:11.913 回答
0

您将 student = 设置为 array_push,它返回一个 int。数组推送通过引用获取一个数组。

http://php.net/manual/en/function.array-push.php

于 2013-05-15T17:59:11.207 回答