2

I'm experimenting with OOP and PHP.

I don't know why I would ever need to do something like this but I'm wondering how it would be done and cant find it online.

class Example{

public $a = 'aye';
public $b = 'bee';
public $c = 'see';

public function how(){
    return (object)array(
                         $this->a,
                         $this->b,
                         $this->c
                        );
    }    
}

$example = new Example;
$how = $example->how(); 
echo $how->1; //I thought would print bee

I'm aware that giving the array keys would let me do

echo $how->beekey //which would give me beekey's value
4

2 回答 2

2

正如此错误报告中所解释的,这基本上是不可能的;数字对象属性是 PHP 中的一种灰色区域。

但是,您可以将对象转换回数组并引用该值:

$arr = (array)$how;
echo $arr[1];

或者,用作单线:

echo current(array_slice((array)$how, 1, 1));

我能给你的最好建议是一开始就不要把它变成一个对象:

public function how()
{
    return array(
        $this->a,
        $this->b,
        $this->c
    );
}    

然后将其引用为$how[1].

顺便说一句,$how->{1} 曾经在 PHP 4 中工作 :)

于 2013-04-24T06:23:20.043 回答
0

使用循环怎么样?

foreach($how as $value)
{
    echo $value .'<br>'; //this print your values: aye<br>bee<br>see
}
于 2013-04-24T06:20:31.107 回答