【问题标题】:Why defined array returns false?为什么定义的数组返回false?
【发布时间】:2013-05-15 17:53:51
【问题描述】:

谁能解释一下为什么当我执行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);

【问题讨论】:

标签: php arrays oop


【解决方案1】:

因为当您使用数组的长度执行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;

【讨论】:

  • 哈哈,领先你 4 秒 :p 给我一个 +1!
  • 你是对的。尽管我已经多次使用array_push 函数,但有时你会忽略一些小事。
【解决方案2】:

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

因此,在调用$this-&gt;students = array_push($this-&gt;students,$name) 之后,你的值是3,这显然不是一个数组。

Documentation

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2021-02-15
      • 2022-08-14
      • 2014-11-17
      • 2014-03-11
      相关资源
      最近更新 更多