【PHP8.x】property_exists関数の使い方

property_exists関数の使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

property_exists関数は、指定されたオブジェクトまたはクラスに指定されたプロパティが存在するかどうかを確認する関数です。この関数は、プロパティが定義されていてアクセス可能であるかどうかを判断するために使用されます。

具体的には、第一引数にオブジェクトまたはクラス名を文字列で指定し、第二引数に確認したいプロパティ名を文字列で指定します。オブジェクトが渡された場合、そのオブジェクトのプロパティの存在が確認されます。クラス名が渡された場合、そのクラスのプロパティの存在が確認されます。

戻り値は、プロパティが存在する場合に true、存在しない場合に false を返します。プロパティが存在しても、アクセス権がない(例えば、privateプロパティに外部からアクセスしようとした)場合は、true が返されます。存在の有無を確認することがこの関数の目的であるためです。

property_exists関数は、オブジェクト指向プログラミングにおいて、特定のオブジェクトやクラスが期待するプロパティを持っているかどうかを事前に確認し、エラーを回避するために役立ちます。例えば、外部から提供されたオブジェクトに対して処理を行う前に、必要なプロパティが存在するかどうかを検証することで、プログラムの安定性を高めることができます。また、クラスの設計段階で、特定のプロパティが存在するかどうかを条件によって変更する場合などにも利用できます。

構文(syntax)

1property_exists(object|string $object_or_class, string $property): bool

引数(parameters)

object|string $object_or_class, string $property

  • object|string $object_or_class: プロパティの存在を確認したいオブジェクト、またはクラス名。
  • string $property: 確認したいプロパティの名前。

戻り値(return)

bool

指定されたプロパティがオブジェクトに存在するかどうかを示す真偽値を返します。プロパティが存在すれば true、存在しなければ false を返します。

サンプルコード

PHPのproperty_existsでプロパティ存在チェックする

1<?php
2
3/**
4 * property_exists 関数のサンプルコード
5 */
6
7class MyClass {
8    public $public_property = 'Public Value';
9    protected $protected_property = 'Protected Value';
10    private $private_property = 'Private Value';
11    public static $static_property = 'Static Value';
12}
13
14// オブジェクトのプロパティ存在チェック
15$obj = new MyClass();
16
17// public プロパティの存在チェック
18var_dump(property_exists($obj, 'public_property')); // bool(true)
19
20// protected プロパティの存在チェック
21var_dump(property_exists($obj, 'protected_property')); // bool(true)
22
23// private プロパティの存在チェック
24var_dump(property_exists($obj, 'private_property')); // bool(true)
25
26// 存在しないプロパティの存在チェック
27var_dump(property_exists($obj, 'non_existent_property')); // bool(false)
28
29// static プロパティの存在チェック (オブジェクト経由)
30var_dump(property_exists($obj, 'static_property')); // bool(true)
31
32// クラス名のプロパティ存在チェック
33var_dump(property_exists('MyClass', 'public_property')); // bool(true)
34
35// static プロパティの存在チェック (クラス名経由)
36var_dump(property_exists('MyClass', 'static_property')); // bool(true)
37?>

property_exists関数は、指定したオブジェクトまたはクラスに、特定のプロパティが定義されているかどうかを確認するための関数です。

この関数は2つの引数を取ります。第1引数には、調査したいオブジェクトのインスタンス、またはクラス名を文字列で指定します。第2引数には、存在を確認したいプロパティの名前を文字列で指定します。関数の戻り値は真偽値(bool型)で、プロパティが存在する場合は true を、存在しない場合は false を返します。

サンプルコードでは、MyClassのオブジェクト$objに対して、様々なプロパティの存在を確認しています。この関数の特徴は、publicprotectedprivateといったアクセス修飾子に関係なく、プロパティが定義されていればtrueを返す点です。これは、プロパティにアクセスできるかどうかではなく、純粋に存在の有無をチェックするためです。staticなプロパティも同様に確認できます。また、オブジェクトのインスタンスだけでなく、クラス名('MyClass')を直接文字列で指定して、プロパティの存在を調べることも可能です。

property_exists関数は、指定されたオブジェクトまたはクラスに指定されたプロパティが存在するかどうかをチェックします。この関数は、public, protected, privateに関わらず、宣言されたすべてのプロパティの存在をtrueで返します。オブジェクト経由だけでなく、クラス名を文字列で指定してもプロパティの存在を確認できます。staticプロパティも同様にチェック可能です。ただし、オブジェクトが存在しない場合やクラス名が誤っている場合はエラーが発生する可能性があるため、事前に存在を確認するようにしましょう。また、配列に対してこの関数を使用しても、意図した結果は得られません。配列のキーの存在を確認する場合は、array_key_exists関数を使用してください。

PHP property_existsでネストされたプロパティをチェックする

1<?php
2
3/**
4 * Represents an Address.
5 */
6class Address
7{
8    public string $street;
9    public string $city;
10    protected string $zipCode; // Protected property to demonstrate visibility
11
12    public function __construct(string $street, string $city, string $zipCode)
13    {
14        $this->street = $street;
15        $this->city = $city;
16        $this->zipCode = $zipCode;
17    }
18}
19
20/**
21 * Represents a User with a nested Address object.
22 */
23class User
24{
25    public string $name;
26    public string $email;
27    public Address $address; // This property holds an instance of the Address class
28    private string $password; // Private property to demonstrate visibility
29
30    public function __construct(string $name, string $email, Address $address, string $password)
31    {
32        $this->name = $name;
33        $this->email = $email;
34        $this->address = $address;
35        $this->password = $password;
36    }
37}
38
39/**
40 * Demonstrates the use of property_exists for properties within an object,
41 * including how to check properties on "nested" objects (objects that are
42 * properties of other objects).
43 */
44function demonstratePropertyExistsNested(): void
45{
46    // 1. Create instances of our classes
47    $userAddress = new Address("123 Main St", "Anytown", "12345");
48    $user = new User("John Doe", "john.doe@example.com", $userAddress, "securepassword");
49
50    echo "--- Checking properties on the top-level User object ---\n";
51
52    // Check for a public property directly on the User object
53    if (property_exists($user, 'name')) {
54        echo "✅ Property 'name' exists on the User object.\n";
55    } else {
56        echo "❌ Property 'name' does NOT exist on the User object.\n";
57    }
58
59    // Check for another public property, which itself is an object ('address')
60    if (property_exists($user, 'address')) {
61        echo "✅ Property 'address' exists on the User object.\n";
62
63        // 2. If 'address' exists and is an object, we can then check its properties.
64        // This is how you handle "nested" property checks.
65        echo "\n--- Checking properties on the nested Address object ---\n";
66
67        // It's good practice to ensure the property is indeed an object before accessing it.
68        if (is_object($user->address)) {
69            echo "The 'address' property is an object. Now checking its internal properties.\n";
70
71            // Check for a public property on the nested Address object
72            if (property_exists($user->address, 'city')) {
73                echo "✅ Property 'city' exists on the nested Address object.\n";
74            } else {
75                echo "❌ Property 'city' does NOT exist on the nested Address object.\n";
76            }
77
78            // Check for a non-existent property on the nested Address object
79            if (property_exists($user->address, 'country')) {
80                echo "❌ Property 'country' does NOT exist on the nested Address object (expected).\n";
81            } else {
82                echo "✅ Property 'country' does NOT exist on the nested Address object (correctly not found).\n";
83            }
84
85            // property_exists can detect protected/private properties as long as they are declared,
86            // regardless of the current scope's visibility rules.
87            if (property_exists($user->address, 'zipCode')) {
88                echo "✅ Property 'zipCode' exists on the nested Address object (even though it's protected).\n";
89            } else {
90                echo "❌ Property 'zipCode' does NOT exist on the nested Address object.\n";
91            }
92        } else {
93            echo "The 'address' property is NOT an object or is null.\n";
94        }
95    } else {
96        echo "❌ Property 'address' does NOT exist on the User object.\n";
97    }
98
99    echo "\n--- Further checks on User object (non-existent and private properties) ---\n";
100
101    // Check for a property that genuinely does not exist anywhere in the class
102    if (property_exists($user, 'age')) {
103        echo "❌ Property 'age' exists on User object (unexpected).\n";
104    } else {
105        echo "✅ Property 'age' does NOT exist on User object (expected).\n";
106    }
107
108    // property_exists correctly finds private properties as well, because it checks
109    // if the property is declared in the class hierarchy.
110    if (property_exists($user, 'password')) {
111        echo "✅ Property 'password' exists on User object (even though it's private).\n";
112    } else {
113        echo "❌ Property 'password' does NOT exist on User object.\n";
114    }
115
116    // 3. Demonstrate using a class name (string) instead of an object instance
117    echo "\n--- Checking properties using a class name (string) ---\n";
118
119    // Check for a public property on the 'User' class
120    if (property_exists('User', 'name')) {
121        echo "✅ Property 'name' exists on class 'User'.\n";
122    } else {
123        echo "❌ Property 'name' does NOT exist on class 'User'.\n";
124    }
125
126    // Check for a non-existent property on the 'User' class
127    if (property_exists('User', 'nonExistentProperty')) {
128        echo "❌ Property 'nonExistentProperty' exists on class 'User' (unexpected).\n";
129    } else {
130        echo "✅ Property 'nonExistentProperty' does NOT exist on class 'User' (expected).\n";
131    }
132
133    // When checking against a class name, property_exists still finds protected/private properties.
134    if (property_exists('Address', 'zipCode')) {
135        echo "✅ Property 'zipCode' exists on class 'Address' (even though it's protected).\n";
136    } else {
137        echo "❌ Property 'zipCode' does NOT exist on class 'Address'.\n";
138    }
139}
140
141// Execute the demonstration function
142demonstratePropertyExistsNested();
143
144?>

PHPのproperty_exists関数は、オブジェクトやクラスに特定のプロパティが宣言されているかを確認するために使います。第一引数には調べたいオブジェクトのインスタンス、またはクラス名を文字列で指定し、第二引数にはプロパティ名を文字列で指定します。プロパティが存在すればtrueを、存在しなければfalseを返します。この関数は、プロパティのアクセス修飾子(publicprotectedprivate)に関わらず、クラスにその名前のプロパティが定義されていればtrueを返す点が重要です。

サンプルコードでは、Userオブジェクトのプロパティ(nameなど)の有無をチェックする基本的な使い方から始まります。特に注目すべきは、Userオブジェクトのaddressプロパティが別のAddressオブジェクトを保持する「ネストされたオブジェクト」の場合の確認方法です。まずUseraddressプロパティがあるかを確認し、次にそのaddressプロパティが本当にオブジェクトであれば、そのaddressオブジェクトに対してさらに内部のプロパティ(cityzipCodeなど)の有無をチェックしています。このように段階的に確認することで、オブジェクトの階層構造をたどってプロパティの存在を安全に検証できます。また、存在しないプロパティの確認や、オブジェクトではなくクラス名を直接指定してプロパティの存在を調べる例も示されています。これにより、実行時エラーを防ぎ、堅牢なコードを記述できるようになります。

property_exists関数は、指定したオブジェクトまたはクラスに特定の名前のプロパティが宣言されているかを確認します。この関数はプロパティの可視性(public, protected, private)に関わらず、宣言されていれば「存在する」と判断するため、アクセス権とは異なる点にご注意ください。ネストされたオブジェクトのプロパティを確認する際は、一度の呼び出しでは直接調べられません。まず親オブジェクトに目的のオブジェクトプロパティが存在するかを確認し、その後、そのネストされたオブジェクトに対して改めてproperty_existsを使用する必要があります。また、ネストされたプロパティにアクセスする前に、is_object()などでそのプロパティが実際にオブジェクトであることを確認すると、予期せぬエラーを防ぎ、より安全にコードを記述できます。第一引数には、オブジェクトのインスタンスだけでなく、クラス名の文字列も指定可能です。

PHPのproperty_exists()でプロパティ存在確認

1<?php
2
3class User
4{
5    public string $name;
6    protected string $email;
7    private string $password;
8    public ?int $age = null; // A property explicitly declared and initialized to null
9
10    public function __construct(string $name, string $email, string $password)
11    {
12        $this->name = $name;
13        $this->email = $email;
14        $this->password = $password;
15    }
16}
17
18// Create an object instance of the User class
19$user = new User('Alice', 'alice@example.com', 'secure_pass');
20
21// Create a generic object (stdClass) and add a dynamic property
22$anonymousObject = new stdClass();
23$anonymousObject->id = 123;
24
25echo "--- Checking properties on object instances ---\n";
26
27// Check for a public property on an object
28echo "Does \$user object have 'name'? " . (property_exists($user, 'name') ? 'Yes' : 'No') . "\n";
29
30// Check for a protected property (property_exists checks existence, not accessibility)
31echo "Does \$user object have 'email'? " . (property_exists($user, 'email') ? 'Yes' : 'No') . "\n";
32
33// Check for a private property
34echo "Does \$user object have 'password'? " . (property_exists($user, 'password') ? 'Yes' : 'No') . "\n";
35
36// Check for a property explicitly declared and initialized to null
37echo "Does \$user object have 'age'? " . (property_exists($user, 'age') ? 'Yes' : 'No') . "\n";
38
39// Check for a non-existent property on the object
40echo "Does \$user object have 'address'? " . (property_exists($user, 'address') ? 'Yes' : 'No') . "\n";
41
42// Check for a dynamically added property on stdClass
43echo "Does \$anonymousObject have 'id'? " . (property_exists($anonymousObject, 'id') ? 'Yes' : 'No') . "\n";
44
45// Check for a non-existent property on stdClass
46echo "Does \$anonymousObject have 'role'? " . (property_exists($anonymousObject, 'role') ? 'Yes' : 'No') . "\n";
47
48
49echo "\n--- Checking properties on class names ---\n";
50
51// Check for a public property using the class name string
52echo "Does class 'User' have 'name'? " . (property_exists('User', 'name') ? 'Yes' : 'No') . "\n";
53
54// Check for a protected property using the class name string
55echo "Does class 'User' have 'email'? " . (property_exists('User', 'email') ? 'Yes' : 'No') . "\n";
56
57// Check for a private property using the class name string
58echo "Does class 'User' have 'password'? " . (property_exists('User', 'password') ? 'Yes' : 'No') . "\n";
59
60// Check for a non-existent property using the class name string
61echo "Does class 'User' have 'startDate'? " . (property_exists('User', 'startDate') ? 'Yes' : 'No') . "\n";
62
63
64echo "\n--- Clarifying 'property_exists' vs 'isset()' ---\n";
65
66// Display the current value of the 'age' property
67echo "Value of \$user->age is: " . var_export($user->age, true) . "\n";
68
69// property_exists returns true because 'age' is a declared property, regardless of its value (even if null)
70echo "Is 'age' property existing in \$user (using property_exists)? " . (property_exists($user, 'age') ? 'Yes' : 'No') . "\n";
71
72// isset() returns false because the 'age' property's value is null
73echo "Is 'age' property set and not null in \$user (using isset())? " . (isset($user->age) ? 'Yes' : 'No') . "\n";
74
75?>

PHPのproperty_exists関数は、指定されたオブジェクトまたはクラスに特定のプロパティ(クラス内で宣言された変数)が存在するかどうかを判定する際に使用します。

第一引数には、プロパティを確認したいオブジェクトのインスタンス、またはクラス名を文字列で指定します。第二引数には、確認したいプロパティの名前を文字列で指定します。戻り値は、プロパティが存在すればtrue、存在しなければfalseという真偽値(bool)です。

この関数は、プロパティのアクセス修飾子(public, protected, private)に関わらず、クラスに宣言されていればtrueを返します。例えば、private$passwordプロパティも、宣言されていれば存在すると判断されます。また、stdClassのようなジェネリックなオブジェクトに動的に追加されたプロパティも検出できます。

重要な点として、プロパティが宣言されており、かつその値がnullである場合でも、property_existstrueを返します。これは、プロパティが存在するかどうかを確認する機能であり、値が「セットされているか(nullではないか)」を確認するisset()関数とは挙動が異なります。サンプルコードの$ageプロパティの例では、property_existstrueですが、isset($user->age)falseとなります。

したがって、property_existsは、あるプロパティがクラス定義やオブジェクトの動的な追加によって実際に「存在するか」を確認したい場合に適しています。

property_existsは、オブジェクトやクラスに指定されたプロパティが「宣言されているか」を確認する関数です。プロパティのアクセス修飾子(public, protected, private)や、その値がnullであるかにかかわらず、宣言されていればtrueを返します。動的に追加されたプロパティも検出可能です。

特にisset()関数との違いに注意が必要です。property_existsはプロパティがnull値でも存在を返しますが、isset()はプロパティが存在し、かつ値がnullではない場合にのみtrueを返します。そのため、「プロパティが宣言されているか」の確認にはproperty_existsを、「有効な値が設定されているか」の確認にはisset()を使い分けてください。「思ったように動かない」と感じる場合、この違いが原因であることが多いです。

property_existsとissetの違いを理解する

1<?php
2
3class PropertyComparisonExample
4{
5    public string $publicPropWithValue = 'Hello World';
6    public ?string $publicPropWithNull = null; // This property exists, but its value is null.
7    protected string $protectedProp = 'I am protected'; // This property exists, but not publicly accessible.
8    private string $privateProp = 'I am private'; // This property exists, but not publicly accessible.
9    // 'nonExistentProp' is intentionally not declared here.
10}
11
12/**
13 * Demonstrates the difference between property_exists() and isset() for class properties.
14 *
15 * property_exists(): Checks if a property is declared in a class or an object,
16 *                    regardless of its value (even if null) and its visibility (public, protected, private).
17 *
18 * isset(): Checks if a variable (or object property) is set AND is not null.
19 *          For object properties, it also requires the property to be accessible from the current scope.
20 */
21function demonstratePropertyChecks(): void
22{
23    $instance = new PropertyComparisonExample();
24
25    echo "--- Public Property with a Value (\$publicPropWithValue) ---" . PHP_EOL;
26    // property_exists() returns true because the property is declared.
27    echo "property_exists(\$instance, 'publicPropWithValue'): ";
28    var_dump(property_exists($instance, 'publicPropWithValue'));
29    // isset() returns true because the property is accessible and its value is not null.
30    echo "isset(\$instance->publicPropWithValue): ";
31    var_dump(isset($instance->publicPropWithValue));
32    echo PHP_EOL;
33
34    echo "--- Public Property with Null Value (\$publicPropWithNull) ---" . PHP_EOL;
35    // property_exists() returns true because the property is declared, even if its value is null.
36    echo "property_exists(\$instance, 'publicPropWithNull'): ";
37    var_dump(property_exists($instance, 'publicPropWithNull'));
38    // isset() returns false because although the property exists and is accessible, its value is null.
39    echo "isset(\$instance->publicPropWithNull): ";
40    var_dump(isset($instance->publicPropWithNull));
41    echo PHP_EOL;
42
43    echo "--- Protected Property (\$protectedProp) ---" . PHP_EOL;
44    // property_exists() returns true because the property is declared in the class, regardless of visibility.
45    echo "property_exists(\$instance, 'protectedProp'): ";
46    var_dump(property_exists($instance, 'protectedProp'));
47    // Note: Attempting isset(\$instance->protectedProp) from outside the class
48    // would result in a Fatal Error due to visibility constraints.
49    echo "// (Attempting isset(\$instance->protectedProp) here would cause a Fatal Error)" . PHP_EOL;
50    echo PHP_EOL;
51
52    echo "--- Private Property (\$privateProp) ---" . PHP_EOL;
53    // property_exists() returns true because the property is declared in the class, regardless of visibility.
54    echo "property_exists(\$instance, 'privateProp'): ";
55    var_dump(property_exists($instance, 'privateProp'));
56    // Note: Attempting isset(\$instance->privateProp) from outside the class
57    // would result in a Fatal Error due to visibility constraints.
58    echo "// (Attempting isset(\$instance->privateProp) here would cause a Fatal Error)" . PHP_EOL;
59    echo PHP_EOL;
60
61    echo "--- Non-existent Property (e.g., 'nonExistentProp') ---" . PHP_EOL;
62    // property_exists() returns false because the property is not declared in the class.
63    echo "property_exists(\$instance, 'nonExistentProp'): ";
64    var_dump(property_exists($instance, 'nonExistentProp'));
65    // isset() returns false because the property does not exist. No error is thrown for non-existent properties.
66    echo "isset(\$instance->nonExistentProp): ";
67    var_dump(isset($instance->nonExistentProp));
68    echo PHP_EOL;
69
70    echo "--- Using property_exists() with a Class Name String ---" . PHP_EOL;
71    // property_exists() can also check static properties or properties of a class without an instance.
72    echo "property_exists(PropertyComparisonExample::class, 'publicPropWithValue'): ";
73    var_dump(property_exists(PropertyComparisonExample::class, 'publicPropWithValue'));
74    echo "property_exists(PropertyComparisonExample::class, 'protectedProp'): ";
75    var_dump(property_exists(PropertyComparisonExample::class, 'protectedProp'));
76    echo "property_exists(PropertyComparisonExample::class, 'nonExistentProp'): ";
77    var_dump(property_exists(PropertyComparisonExample::class, 'nonExistentProp'));
78    echo PHP_EOL;
79}
80
81// Execute the function to see the comparisons
82demonstratePropertyChecks();

property_exists()関数は、指定されたオブジェクトまたはクラスに、指定された名前のプロパティが存在するかどうかを確認するために使用します。PHP 8.4で利用可能です。この関数は、プロパティの可視性(public, protected, private)や、プロパティの値がnullであるかどうかに関わらず、プロパティが宣言されていればtrueを返します。

引数には、オブジェクトまたはクラス名を文字列で指定する $object_or_class と、確認するプロパティ名を文字列で指定する $property を渡します。クラス名を文字列で渡す場合は、PropertyComparisonExample::classのように::classを使用します。

戻り値はbool型で、プロパティが存在する場合はtrue、存在しない場合はfalseを返します。

サンプルコードでは、property_exists()isset()の違いを明確に示しています。isset()はプロパティが存在し、かつnullでない場合にtrueを返しますが、property_exists()はプロパティの存在のみを確認します。また、isset()はアクセス可能なプロパティに対してのみ使用できますが、property_exists()protectedprivateなプロパティの存在も確認できます。存在しないプロパティに対してisset()を使用してもエラーは発生しませんが、protectedprivateなプロパティに対してアクセスしようとするとFatal Errorが発生します。property_exists()を使うことで、オブジェクトが特定のプロパティを持っているかどうかを安全に確認できます。

property_exists()isset()は、プロパティの存在確認で異なる役割を持ちます。property_exists()は、クラスやオブジェクトにプロパティが宣言されているかを確認し、null値やアクセス制限(protectedprivate)に関わらずtrueを返します。一方、isset()は、プロパティが存在し、かつnullでない場合にtrueを返します。isset()は、アクセス可能なプロパティに対してのみ使用できます。protectedprivateなプロパティに外部からisset()を使用すると、致命的なエラーが発生します。property_exists()は、クラス名を文字列で指定して、インスタンス化せずにプロパティの存在を確認できます。プロパティの存在のみを確認したい場合はproperty_exists()、値が設定されているか確認したい場合はisset()を使い分けましょう。

関連コンテンツ