« Attribute::__construct
AllowDynamicProperties::__construct »

AllowDynamicProperties アトリビュート

(PHP 8 >= 8.2.0)

はじめに

このアトリビュートを使うと、 クラスに 動的なプロパティ を許可することをマークできます。

注意:

アトリビュート自体は継承されませんが、 AllowDynamicProperties アトリビュートの効果は継承されます。 このアトリビュートでマークされたクラスの子クラスは、 明示的にアトリビュートを宣言していなくても、動的なプロパティが許可されます。

クラス概要

#[\Attribute(\Attribute::TARGET_CLASS)]
final class AllowDynamicProperties {
/* メソッド */
public function __construct()
}

例

動的なプロパティは、PHP 8.2.0 以降は推奨されなくなりました。 よって、このアトリビュートでクラスをマークせずに、 動的なプロパティを使うと、 推奨されない警告が発生します。

例1 存在しないプロパティに対する AllowDynamicProperties

<?php
class DefaultBehaviour { }

#[\AllowDynamicProperties]
class ClassAllowsDynamicProperties { }

$o1 = new DefaultBehaviour();
$o2 = new ClassAllowsDynamicProperties();

$o1->nonExistingProp = true;
$o2->nonExistingProp = true;
?>

上の例の PHP 8.2 での出力は、このようになります。:

Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 10

例2 継承クラスでの存在しないプロパティに対する AllowDynamicProperties

<?php
class DefaultBehaviour { }

#[\AllowDynamicProperties]
class ClassAllowsDynamicProperties { }

class InheritedClassAllowsDynamicProperties extends ClassAllowsDynamicProperties { }

$o1 = new DefaultBehaviour();
$o2 = new InheritedClassAllowsDynamicProperties();

$o1->nonExistingProp = true;
$o2->nonExistingProp = true;
?>

上の例の PHP 8.2 での出力は、このようになります。:

Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 12

目次

関連キーワード:
AllowDynamicProperties   アトリビュート   プロパティ   DefaultBehaviour   nonExistingProp   construct   ClassAllowsDynamicProperties   Attribute   マーク   継承   許可   概要   推奨   Deprecated   Creation   property   deprecated   line   InheritedClassAllowsDynamicProperties   自体   効果   明示   宣言   final   extends
関連する関数・ページ:
allowdynamicproperties.construct   reserved.attributes   language.attributes   class.attribute   language.attributes.classes   class.deprecated