为什么定义的数组返回false?

时间:2013-05-15 17:53:51

标签: php arrays oop

有人可以解释一下为什么当我这样做时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);

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

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

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

Documentation

答案 2 :(得分:0)

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

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