1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.properties" xmlns="http://docbook.org/ns/docbook">
<title>Properties</title>
<para>
Class member variables are called <emphasis>properties</emphasis>.
They may be referred to using other terms such as <emphasis>fields</emphasis>,
but for the purposes of this reference <emphasis>properties</emphasis>
will be used. They are defined by using at least one modifier (such as
<xref linkend="language.oop5.visibility"/>,
<xref linkend="language.oop5.static"/>,
or, as of PHP 8.1.0, <link linkend="language.oop5.properties.readonly-properties">readonly</link>),
optionally (except for <code>readonly</code> properties), as of PHP 7.4,
followed by a type declaration, followed by a normal variable declaration.
This declaration may include an initialization, but this initialization
must be a <link linkend="language.constants">constant</link> value.
</para>
<note>
<para>
An obsolete way of declaring class properties, is by using the
<literal>var</literal> keyword instead of a modifier.
</para>
</note>
<note>
<simpara>
A property declared without a <xref linkend="language.oop5.visibility"/>
modifier will be declared as <literal>public</literal>.
</simpara>
</note>
<para>
Within class methods non-static properties may be accessed by using
<literal>-></literal> (Object Operator): <varname>$this->property</varname>
(where <literal>property</literal> is the name of the property).
Static properties are accessed by using the <literal>::</literal> (Double Colon):
<varname>self::$property</varname>. See <xref linkend="language.oop5.static" />
for more information on the difference between static and non-static properties.
</para>
<para>
The pseudo-variable <varname>$this</varname> is available inside
any class method when that method is called from within an object context.
<varname>$this</varname> is the value of the calling object.
</para>
<para>
<example>
<title>Property declarations</title>
<programlisting role="php">
<![CDATA[
<?php
class SimpleClass
{
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = [true, false];
public $var8 = <<<'EOD'
hello world
EOD;
// Without visibility modifier:
static $var9;
readonly int $var10;
}
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
There are various functions to handle classes and objects.
See the <link linkend="ref.classobj">Class/Object Functions</link>
reference.
</para>
</note>
<sect2 xml:id="language.oop5.properties.typed-properties">
<title>Type declarations</title>
<para>
As of PHP 7.4.0, property definitions can include
<xref linkend="language.types.declarations" />,
with the exception of <type>callable</type>.
<example>
<title>Example of typed properties</title>
<programlisting role="php">
<![CDATA[
<?php
class User
{
public int $id;
public ?string $name;
public function __construct(int $id, ?string $name)
{
$this->id = $id;
$this->name = $name;
}
}
$user = new User(1234, null);
var_dump($user->id);
var_dump($user->name);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
int(1234)
NULL
]]>
</screen>
</example>
</para>
<para>
Typed properties must be initialized before accessing, otherwise an
<classname>Error</classname> is thrown.
<example>
<title>Accessing properties</title>
<programlisting role="php">
<![CDATA[
<?php
class Shape
{
public int $numberOfSides;
public string $name;
public function setNumberOfSides(int $numberOfSides): void
{
$this->numberOfSides = $numberOfSides;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getNumberOfSides(): int
{
return $this->numberOfSides;
}
public function getName(): string
{
return $this->name;
}
}
$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());
$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(8) "triangle"
int(3)
string(6) "circle"
Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization
]]>
</screen>
</example>
</para>
</sect2>
<sect2 xml:id="language.oop5.properties.readonly-properties">
<title>Readonly properties</title>
<para>
As of PHP 8.1.0, a property can be declared with the <literal>readonly</literal> modifier,
which prevents modification of the property after initialization. Prior to PHP 8.4.0
a <literal>readonly</literal> property is implicitly private-set, and may only be written to
from the same class. As of PHP 8.4.0, <literal>readonly</literal> properties are implicitly
<link linkend="language.oop5.visibility-members-aviz"><literal>protected(set)</literal></link>,
so may be set from child classes. That may be overridden
explicitly if desired.
<example>
<title>Example of readonly properties</title>
<programlisting role="php">
<![CDATA[
<?php
class Test {
public readonly string $prop;
public function __construct(string $prop) {
// Legal initialization.
$this->prop = $prop;
}
}
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>
]]>
</programlisting>
</example>
<note>
<para>
The readonly modifier can only be applied to <link linkend="language.oop5.properties.typed-properties">typed properties</link>.
A readonly property without type constraints can be created using the <xref linkend="language.types.mixed"/> type.
</para>
</note>
<note>
<para>
Readonly static properties are not supported.
</para>
</note>
</para>
<para>
A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an <classname>Error</classname> exception.
<example>
<title>Illegal initialization of readonly properties</title>
<programlisting role="php">
<![CDATA[
<?php
class Test1 {
public readonly string $prop;
}
$test1 = new Test1;
// Illegal initialization outside of private scope.
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Test {
// Fatal error: Readonly property Test::$prop cannot have default value
public readonly int $prop = 42;
}
?>
]]>
</programlisting>
</informalexample>
</para>
</note>
<note>
<para>
Readonly properties cannot be <function>unset</function> once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared.
</para>
</note>
<para>
Modifications are not necessarily plain assignments, all of the following will also result in an <classname>Error</classname> exception:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Test {
public function __construct(
public readonly int $i = 0,
public readonly array $ary = [],
) {}
}
$test = new Test;
$test->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Test {
public function __construct(public readonly object $obj) {}
}
$test = new Test(new stdClass);
// Legal interior mutation.
$test->obj->foo = 1;
// Illegal reassignment.
$test->obj = new stdClass;
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
As of PHP 8.3.0, readonly properties can be reinitialized when cloning an object
using the <link linkend="object.clone">__clone()</link> method.
<example>
<title>Readonly properties and cloning</title>
<programlisting role="php">
<![CDATA[
<?php
class Test1 {
public readonly ?string $prop;
public function __clone() {
$this->prop = null;
}
public function setProp(string $prop): void {
$this->prop = $prop;
}
}
$test1 = new Test1;
$test1->setProp('foobar');
$test2 = clone $test1;
var_dump($test2->prop); // NULL
?>
]]>
</programlisting>
</example>
</para>
</sect2>
<sect2 xml:id="language.oop5.properties.dynamic-properties">
<title>Dynamic properties</title>
<para>
If trying to assign to a non-existent property on an &object;,
PHP will automatically create a corresponding property.
This dynamically created property will <emphasis>only</emphasis> be
available on this class instance.
</para>
<warning>
<simpara>
Dynamic properties are deprecated as of PHP 8.2.0.
It is recommended to declare the property instead.
To handle arbitrary property names, the class should implement the magic
methods <link linkend="object.get">__get()</link> and
<link linkend="object.set">__set()</link>.
At last resort the class can be marked with the
<code>#[\AllowDynamicProperties]</code> attribute.
</simpara>
</warning>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
|