3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** 従来の普通のクラス内で定義されていないプロパティをインスタンス化した後に生やすと非推奨の警告が出るようになりました */ class User { public $name; } // この非推奨の警告は次の様に出ます $user = new User(); $user->last_name = 'Doe'; // Deprecated: Creation of dynamic property User::$last_name is deprecated in xxx.php on line 9 /** stdClass、いわゆる無名の汎用的な空のクラスでは動的にプロパティを生やしても問題ないです。 */ $user = new stdClass(); $user->last_name = 'Doe'; // 何の警告も発生しない // stdClass は new stdClass() 以外でも生成されます。よくあるのは json_decode や SQL の結果です。 $user = json_decode('{}', false, JSON_THROW_ON_ERROR); $user->last_name = 'Doe'; // 何の警告も発生しない /** PHP8.2 から増えたアトリビュートであるAllowDynamicPropertiesをつけることでも動的にプロパティを生やすことが許されます */ // @see https://www.php.net/manual/ja/class.allow-dynamic-properties.php #[\AllowDynamicProperties] class UserWithAllowDynamicProperties { public $name; } $user = new UserWithAllowDynamicProperties(); $user->last_name = 'Doe'; // 何の警告も発生しない /** マジックメソッドである __set を使う場合も動的にプロパティを生やす様な書き方が許されます */ // @see https://www.php.net/manual/ja/language.oop5.overloading.php#object.set // 今回の動的なプロパティの作成の非推奨化は厳密にはクラスで宣言されていないプロパティの扱いを非推奨に寄せるものです。 class UserWithSetter { public $name; protected array $attr = []; public function __set(string $name, $value): void { $this->attr[$name] = $value; } } $user = new UserWithSetter(); $user->last_name = 'Doe'; // 何の警告も発生しない
Output for 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
Deprecated: Creation of dynamic property User::$last_name is deprecated in /in/nmQkc on line 9
Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33
Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) in /in/nmQkc on line 36
Process exited with code 255.
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33
Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting variable (T_VARIABLE) in /in/nmQkc on line 36
Process exited with code 255.
Output for 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29
Parse error: syntax error, unexpected T_ARRAY, expecting T_VARIABLE in /in/nmQkc on line 36
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Parse error: parse error, unexpected T_ARRAY, expecting T_VARIABLE in /in/nmQkc on line 36
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/nmQkc on line 5
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/nmQkc on line 5
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /in/nmQkc on line 5
Process exited with code 255.

preferences:
276.89 ms | 401 KiB | 469 Q