-1
<?php    

class ffooo
{
    public $arr;

    function __construct()
    {
        $arr=array();
    }

    function add($val)
    {
        $arr[]=$val;
    }

    function get($ind)
    {
        return $arr[$ind];
    }
}

$cont=new ffooo();
$cont->add("derek",'chmo');
echo $cont->get(0);
var_dump($cont);

任何人都可以解释为什么我的数组 $arr 在方法 add($val) 之后为 NULL 吗?我尝试在方法“add”中回显数组 $arr,并且在这个方法中 $arr 包含来值;但在另一种方法中它变成了NULL?什么是魔法?我不明白逻辑(

4

5 回答 5

1

因为它仅在本地定义。要使用类成员,您必须使用 $this;

$this->arr
于 2012-07-20T21:54:29.440 回答
1

That's because you declare a variable $arr every time. And in every method it's just new, as functions have their own scope.

You need to set a property, like that: $this->arr = array(...);. Properties exist in object scope, so they are accessible from every method.

于 2012-07-20T21:54:48.303 回答
0

You declared the function with one argument:

function add($val) {}

But pass to it two ones. And why do you use local copies of the class property in every function? Correct your code before talking about magic :)

于 2012-07-20T21:54:50.380 回答
0

Use $this->arr instead of $arr in all methods' bodies.

于 2012-07-20T21:55:21.903 回答
0

You forgot to use $this, please see the code below.

<?php    

class ffooo
{
    public $arr;

    function __construct()
    {
        $this->arr = array();
    }

    function add($val)
    {
        $this->arr[] = $val;
    }

    function get($ind)
    {
        return $this->arr[$ind];
    }
}

$cont=new ffooo();
$cont->add('derek');
echo $cont->get(0);
var_dump($cont);
于 2012-07-20T21:55:52.517 回答