Skip to content

Commit 623a270

Browse files
zimzatlacatoire
andauthored
property_exists: Update example to show more scenarios. (#4508)
* property_exists: Update example to show more scenarios. The main thing to highlight is that property visibility and `__get` and `__isset` is not checked. * docs(property_exists): split into two examples, keep original and add visibility/magic methods example * fix: move example description outside <example> element * Use simpara for the inline-only paragraph --------- Co-authored-by: lacatoire <la.catoire@gmail.com>
1 parent e549ce1 commit 623a270

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

reference/classobj/functions/property-exists.xml

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,68 @@ myClass::test();
8787
</programlisting>
8888
</example>
8989
</para>
90+
<simpara>
91+
<function>property_exists</function> returns &true; regardless of property
92+
visibility, detects dynamic properties added to instances (when the class
93+
uses <literal>#[AllowDynamicProperties]</literal>), and ignores
94+
<link linkend="language.oop5.overloading.members"><literal>__isset</literal></link>
95+
and <literal>__get</literal> magic methods.
96+
</simpara>
97+
<para>
98+
<example>
99+
<title>Visibility, dynamic properties, and magic methods</title>
100+
<programlisting role="php">
101+
<![CDATA[
102+
<?php
103+
104+
#[AllowDynamicProperties]
105+
class MyClass {
106+
public $public;
107+
private $private;
108+
static protected $protectedStatic;
109+
110+
// ignored by property_exists
111+
public function __isset(string $name): bool {
112+
return true;
113+
}
114+
115+
// ignored by property_exists
116+
public function __get(string $name): string {
117+
return '';
118+
}
119+
}
120+
121+
$instance = new MyClass();
122+
$instance->instanced = 'abc';
123+
124+
var_dump(property_exists($instance, 'public')); // true (public)
125+
var_dump(property_exists($instance, 'private')); // true (visibility ignored)
126+
var_dump(property_exists($instance, 'protectedStatic')); // true (visibility ignored)
127+
var_dump(property_exists($instance, 'instanced')); // true (dynamic property on instance)
128+
var_dump(property_exists($instance, 'undefined')); // false (not declared, __isset ignored)
129+
130+
var_dump(property_exists(MyClass::class, 'public')); // true
131+
var_dump(property_exists(MyClass::class, 'instanced')); // false (dynamic props not on class)
132+
var_dump(property_exists(MyClass::class, 'undefined')); // false
133+
134+
?>
135+
]]>
136+
</programlisting>
137+
&example.outputs;
138+
<screen>
139+
<![CDATA[
140+
bool(true)
141+
bool(true)
142+
bool(true)
143+
bool(true)
144+
bool(false)
145+
bool(true)
146+
bool(false)
147+
bool(false)
148+
]]>
149+
</screen>
150+
</example>
151+
</para>
90152
</refsect1>
91153

92154
<refsect1 role="notes">

0 commit comments

Comments
 (0)