PHPで、オブジェクト内の配列の要素にアクセスしたいとき

class Hoge
{
    public $foo = array(1, 2, 3);
}
$foo = 'foo';
$hoge = new Hoge;
echo $hoge->{$foo}[1] . "\n";
echo $hoge->foo[1] . "\n";

あまり使わないと思いますが、、get_object_varsと組み合わせて使いたい場面が出たので。
{}が重要。
$fooを{}で囲わないと$foo[1]が優先されて”o”になってしまい(文字列にも添え字でアクセスできてしまうので)エラーになるようだ。

PHP Notice:  Undefined property:  Hoge::$o

最初はarray_sliceとcurrentを併用していた。

This entry was posted in いじる. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Page optimized by WP Minify WordPress Plugin