使用面向对象编程在PHP中显示数组

I'm experimenting with PHP and object oriented programming in PHP. When I try to run the following displayArray function, it does not display the line at all. Does anyone know what I'm doing wrong?

<?php
class Student
{
    var $name;
    var $arr;

    function Student()
    {
        $this->name = "bob";
        $this->addnametostring("Hello there ");
        $this->arr = array();

        for($i=0; $i<30; $i++) {
            $arr[$i] = rand(0,100);
        }
    }

    function addnametostring($s)
    {
        $s.= " " . $this->name;
        echo "$s <br>";
    }

    function displayArray($amt)
    {
        foreach($this->arr as $key) { 
        //why is this not working
        echo "<br>hello: ".$key;
    }
}

}

$student = new Student;
echo "<br>";
$student->displayArray(20);

?>

Change this

for($i=0; $i<30; $i++){
   $arr[$i] = rand(0,100);
}

to

for($i=0; $i<30; $i++){
   $this->arr[$i] = rand(0,100);
}

EDIT: Did not notice you are missing your constructor, so your entire class should look like this

class Student(){

    var $name;
    var $arr;

    public function __construct() {
        $this->name = "bob";
        $this->addnametostring("Hello there ");
        $this->arr = array();

        for($i=0; $i<30; $i++){
            $this->arr[$i] = rand(0,100);
        }

    }

    function addnametostring($s){
        $s.= " " . $this->name;
        echo "$s <br>";
    }

    function displayArray($amt){
        foreach($this->arr as $key){
            //why is this not working
            echo "<br>hello: ".$key;
        }
    }
}

in php constructer is as follow

function __construct(){
//some code
}

so you are not calling student function.

You can use a constructor to easily assign the array when you first call the class.

<?php
class Student
{
    public $name;
    public $arr;

    function __construct()
    {
        $this->name = "bob";
        $this->addnametostring("Hello there ");
        $this->arr = array();

        for($i=0; $i<30; $i++) {
            $this -> arr[$i] = rand(0,100);
        }
    }

    function addnametostring($s)
    {
        $s.= " " . $this->name;
        echo "$s <br>";
    }

    function displayArray()
    {
        foreach($this->arr as $key) { 
            //why is this not working
            echo "<br>hello: ".$key;
        }
    }
}

Then,

$student = new Student;
echo "<br>";
$student-> displayArray();

I'm not sure why you had $amt variable.

Thanks.