我试图打印数组$ array1但它显示错误消息

时间:2015-06-25 16:51:43

标签: php arrays

我尝试打印数组$array1,但它显示错误消息为

  

注意:未定义的变量:第16行的D:\ xampp \ htdocs \ trainig \ Day4 \ accessmod.php中的array1警告:在D:\ xampp \ htdocs \ trainig \ Day4 \ accessmod中为foreach()提供的参数无效。第16行的PHP

<?php 
    class AccessMode
    {
    public $integer_member = 1;
    protected $float_number = 2.5;
    private $string = "Tony";
    public $array1 = [5, 7, 9];
    function print_properties(){
        echo "public integer: ".$this->integer_member;
        echo "<br>";
        echo "protected float: ".$this->float_number;
        echo "<br>";
        echo "private string: ".$this->string;
        echo "<br>";
        echo "public array: ";
        foreach ($array1 as $av){
            echo $av." ";  
        }

       }

    }
     $a = new AccessMode();
    echo "<br>";
    echo " From AccessMode class <br>";
    $a->print_properties();
    ?>

1 个答案:

答案 0 :(得分:1)

您想要访问类成员而不是变量,因此您需要使用$this。代码应该是:

foreach ($this->array1 as $av) {

然后输出是:

From AccessMode class
public integer: 1
protected float: 2.5
private string: Tony
public array: 5 7 9 

代码是:

<?php
class AccessMode
{
    public $integer_member = 1;
    protected $float_number = 2.5;
    private $string = "Tony";
    public $array1 = [5, 7, 9];

    function print_properties()
    {
        echo "public integer: " . $this->integer_member;
        echo "<br>";
        echo "protected float: " . $this->float_number;
        echo "<br>";
        echo "private string: " . $this->string;
        echo "<br>";
        echo "public array: ";
        foreach ($this->array1 as $av)
        {
            echo $av . " ";
        }

    }

}

$a = new AccessMode();
echo "<br>";
echo " From AccessMode class <br>";
$a->print_properties();
?>