LoginSignup
6
6

More than 5 years have passed since last update.

php 覚書 1 プロパティアクセス編

Posted at

案件が変わったので今後は php の投稿が多くなる見込み

<?php
class A {
  public $b = "hoge"; // 良い子は プロパティ を public で定義しちゃダメだゾ
}

$a = new A();
$c = "b";

var_dump($a->b);      // string(4) "hoge"
var_dump($a->{'b'});  // string(4) "hoge"
var_dump($a->$c);     // string(4) "hoge"
var_dump($a->{$c});   // string(4) "hoge"

2個目があるおかげで、json 文字列をデコードする時も問題なく行える。

<?php
$jsonStr = <<<EOT
{
  "normal": "hoge",
  "a b": "fuga",
  "a->b": "expected",
  "a": {"b": "unexpected"}
}
EOT;
$json = json_decode($jsonStr);
$normal = "normal";
$space = "a b";
$arrow = "a->b";

var_dump($json->normal);      // string(4) "hoge"
var_dump($json->{'normal'});  // string(4) "hoge"
var_dump($json->$normal);     // string(4) "hoge"
var_dump($json->{$normal});   // string(4) "hoge"

// var_dump($json->a b);      // Parse error
var_dump($json->{'a b'});     // string(4) "fuga"
var_dump($json->$space);      // string(4) "fuga"
var_dump($json->{$space});    // string(4) "fuga"

var_dump($json->a->b);        // string(10) "unexpected"
var_dump($json->{'a->b'});    // string(8) "expected"
var_dump($json->$arrow);      // string(8) "expected"
var_dump($json->{$arrow});    // string(8) "expected"

個人的には、オブジェクトのプロパティと連想配列のキーとの区別が無い JavaScript の方が好き。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6