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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.magic" xmlns="http://docbook.org/ns/docbook">
<title>Magic Methods</title>
<para>
Magic methods are special methods which override PHP's default's action
when certain actions are performed on an object.
</para>
<caution>
<simpara>
All methods names starting with <literal>__</literal> are reserved by PHP.
Therefore, it is not recommended to use such method names unless overriding
PHP's behavior.
</simpara>
</caution>
<para>
The following method names are considered magical:
<!-- Should be an itemized list ? -->
<link linkend="object.construct">__construct()</link>,
<link linkend="object.destruct">__destruct()</link>,
<link linkend="object.call">__call()</link>,
<link linkend="object.callstatic">__callStatic()</link>,
<link linkend="object.get">__get()</link>,
<link linkend="object.set">__set()</link>,
<link linkend="object.isset">__isset()</link>,
<link linkend="object.unset">__unset()</link>,
<link linkend="object.sleep">__sleep()</link>,
<link linkend="object.wakeup">__wakeup()</link>,
<link linkend="object.serialize">__serialize()</link>,
<link linkend="object.unserialize">__unserialize()</link>,
<link linkend="object.tostring">__toString()</link>,
<link linkend="object.invoke">__invoke()</link>,
<link linkend="object.set-state">__set_state()</link>,
<link linkend="object.clone">__clone()</link>, and
<link linkend="object.debuginfo">__debugInfo()</link>.
</para>
<warning>
<!-- See for a code example of this behaviour: https://3v4l.org/Bov34 -->
<simpara>
All magic methods, with the exception of
<link linkend="object.construct">__construct()</link>,
<link linkend="object.destruct">__destruct()</link>, and
<link linkend="object.clone">__clone()</link>,
<emphasis>must</emphasis> be declared as <literal>public</literal>,
otherwise an <constant>E_WARNING</constant> is emitted.
Prior to PHP 8.0.0, no diagnostic was emitted for the magic methods
<link linkend="object.sleep">__sleep()</link>,
<link linkend="object.wakeup">__wakeup()</link>,
<link linkend="object.serialize">__serialize()</link>,
<link linkend="object.unserialize">__unserialize()</link>, and
<link linkend="object.set-state">__set_state()</link>.
</simpara>
</warning>
<warning>
<para>
If type declarations are used in the definition of a magic method, they
must be identical to the signature described in this document.
Otherwise, a fatal error is emitted.
Prior to PHP 8.0.0, no diagnostic was emitted.
However, <link linkend="object.construct">__construct()</link> and
<link linkend="object.destruct">__destruct()</link> must not declare a return type;
otherwise a fatal error is emitted.
</para>
</warning>
<sect2 xml:id="language.oop5.magic.sleep">
<title>
<link linkend="object.sleep">__sleep()</link> and
<link linkend="object.wakeup">__wakeup()</link>
</title>
<methodsynopsis xml:id="object.sleep">
<modifier>public</modifier> <type>array</type><methodname>__sleep</methodname>
<void/>
</methodsynopsis>
<methodsynopsis xml:id="object.wakeup">
<modifier>public</modifier> <type>void</type><methodname>__wakeup</methodname>
<void/>
</methodsynopsis>
<para>
<function>serialize</function> checks if the class has a function with
the magic name <link linkend="object.sleep">__sleep()</link>. If so, that function is
executed prior to any serialization. It can clean up the object
and is supposed to return an array with the names of all variables
of that object that should be serialized.
If the method doesn't return anything then &null; is serialized and
<constant>E_NOTICE</constant> is issued.
</para>
<note>
<para>
It is not possible for <link linkend="object.sleep">__sleep()</link> to return names of
private properties in parent classes. Doing this will result in an
<constant>E_NOTICE</constant> level error.
Use <link linkend="object.serialize">__serialize()</link> instead.
</para>
</note>
<note>
<para>
As of PHP 8.0.0, returning a value which is not an array from <link linkend="object.sleep">__sleep()</link> generates a warning. Previously, it generated a notice.
</para>
</note>
<para>
The intended use of <link linkend="object.sleep">__sleep()</link> is to commit pending
data or perform similar cleanup tasks. Also, the function is
useful if a very large object doesn't need to be saved completely.
</para>
<para>
Conversely, <function>unserialize</function> checks for the
presence of a function with the magic name
<link linkend="object.wakeup">__wakeup()</link>. If present, this function can
reconstruct any resources that the object may have.
</para>
<para>
The intended use of <link linkend="object.wakeup">__wakeup()</link> is to
reestablish any database connections that may have been lost
during serialization and perform other reinitialization
tasks.
</para>
<example>
<title>Sleep and wakeup</title>
<programlisting role="php">
<![CDATA[
<?php
class Connection
{
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
}?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.magic.serialize">
<title>
<link linkend="object.serialize">__serialize()</link> and
<link linkend="object.unserialize">__unserialize()</link>
</title>
<methodsynopsis xml:id="object.serialize">
<modifier>public</modifier> <type>array</type><methodname>__serialize</methodname>
<void/>
</methodsynopsis>
<methodsynopsis xml:id="object.unserialize">
<modifier>public</modifier> <type>void</type><methodname>__unserialize</methodname>
<methodparam><type>array</type><parameter>data</parameter></methodparam>
</methodsynopsis>
<para>
<function>serialize</function> checks if the class has a function with
the magic name <link linkend="object.serialize">__serialize()</link>. If so, that function is
executed prior to any serialization. It must construct and return an associative array of key/value pairs
that represent the serialized form of the object. If no array is returned a <classname>TypeError</classname>
will be thrown.
</para>
<note>
<para>
If both <link linkend="object.serialize">__serialize()</link> and <link linkend="object.sleep">__sleep()</link>
are defined in the same object, only <link linkend="object.serialize">__serialize()</link> will be called.
<link linkend="object.sleep">__sleep()</link> will be ignored. If the object implements the <link linkend="class.serializable">Serializable</link>
interface, the interface's <literal>serialize()</literal> method will be ignored and <link linkend="object.serialize">__serialize()</link>
used instead.
</para>
</note>
<para>
The intended use of <link linkend="object.serialize">__serialize()</link> is to define a serialization-friendly
arbitrary representation of the object. Elements of the array may correspond to properties of the object but
that is not required.
</para>
<para>
Conversely, <function>unserialize</function> checks for the
presence of a function with the magic name
<link linkend="object.unserialize">__unserialize()</link>. If present, this function will be passed the
restored array that was returned from <link linkend="object.serialize">__serialize()</link>. It may
then restore the properties of the object from that array as appropriate.
</para>
<note>
<para>
If both <link linkend="object.unserialize">__unserialize()</link> and <link linkend="object.wakeup">__wakeup()</link>
are defined in the same object, only <link linkend="object.unserialize">__unserialize()</link> will be called.
<link linkend="object.wakeup">__wakeup()</link> will be ignored.
</para>
</note>
<note>
<para>
This feature is available as of PHP 7.4.0.
</para>
</note>
<example>
<title>Serialize and unserialize</title>
<programlisting role="php">
<![CDATA[
<?php
class Connection
{
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __serialize(): array
{
return [
'dsn' => $this->dsn,
'user' => $this->username,
'pass' => $this->password,
];
}
public function __unserialize(array $data): void
{
$this->dsn = $data['dsn'];
$this->username = $data['user'];
$this->password = $data['pass'];
$this->connect();
}
}?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.magic.tostring">
<title><link linkend="object.tostring">__toString()</link></title>
<methodsynopsis xml:id="object.tostring">
<modifier>public</modifier> <type>string</type><methodname>__toString</methodname>
<void/>
</methodsynopsis>
<para>
The <link linkend="object.tostring">__toString()</link> method allows a class to decide
how it will react when it is treated like a string. For example,
what <literal>echo $obj;</literal> will print.
</para>
<warning>
<para>
As of PHP 8.0.0, the return value follows standard PHP type semantics,
meaning it will be coerced into a <type>string</type> if possible and if
<link linkend="language.types.declarations.strict">strict typing</link>
is disabled.
</para>
<para>
A <interfacename>Stringable</interfacename> object will
<emphasis>not</emphasis> be accepted by a <type>string</type> type declaration if
<link linkend="language.types.declarations.strict">strict typing</link>
is enabled. If such behaviour is wanted the type declaration must accept
<interfacename>Stringable</interfacename> and <type>string</type> via a union type.
</para>
<para>
As of PHP 8.0.0, any class that contains a <link linkend="object.tostring">__toString()</link>
method will also implicitly implement the <interfacename>Stringable</interfacename> interface, and will
thus pass type checks for that interface. Explicitly implementing the interface anyway is
recommended.
</para>
<para>
In PHP 7.4, the returned value <emphasis>must</emphasis> be a
<type>string</type>, otherwise an <classname>Error</classname> is thrown.
</para>
<para>
Prior to PHP 7.4.0, the returned value <emphasis>must</emphasis> be a
<type>string</type>, otherwise a fatal <constant>E_RECOVERABLE_ERROR</constant>
is emitted.
</para>
</warning>
<warning>
<simpara>
It was not possible to throw an exception from within a
<link linkend="object.tostring">__toString()</link>
method prior to PHP 7.4.0. Doing so will result in a fatal error.
</simpara>
</warning>
<example>
<title>Simple example</title>
<programlisting role="php">
<![CDATA[
<?php
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.magic.invoke">
<title><link linkend="object.invoke">__invoke()</link></title>
<methodsynopsis xml:id="object.invoke">
<type>mixed</type><methodname>__invoke</methodname>
<methodparam rep="repeat"><parameter>values</parameter></methodparam>
</methodsynopsis>
<para>
The <link linkend="object.invoke">__invoke()</link> method is called when a script tries to
call an object as a function.
</para>
<example>
<title>Using <link linkend="object.invoke">__invoke()</link></title>
<programlisting role="php">
<![CDATA[
<?php
class CallableClass
{
public function __invoke($x)
{
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
int(5)
bool(true)
]]>
</screen>
</example>
<example>
<title>Using <link linkend="object.invoke">__invoke()</link></title>
<programlisting role="php">
<![CDATA[
<?php
class Sort
{
private $key;
public function __construct(string $key)
{
$this->key = $key;
}
public function __invoke(array $a, array $b): int
{
return $a[$this->key] <=> $b[$this->key];
}
}
$customers = [
['id' => 1, 'first_name' => 'John', 'last_name' => 'Do'],
['id' => 3, 'first_name' => 'Alice', 'last_name' => 'Gustav'],
['id' => 2, 'first_name' => 'Bob', 'last_name' => 'Filipe']
];
// sort customers by first name
usort($customers, new Sort('first_name'));
print_r($customers);
// sort customers by last name
usort($customers, new Sort('last_name'));
print_r($customers);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[0] => Array
(
[id] => 3
[first_name] => Alice
[last_name] => Gustav
)
[1] => Array
(
[id] => 2
[first_name] => Bob
[last_name] => Filipe
)
[2] => Array
(
[id] => 1
[first_name] => John
[last_name] => Do
)
)
Array
(
[0] => Array
(
[id] => 1
[first_name] => John
[last_name] => Do
)
[1] => Array
(
[id] => 2
[first_name] => Bob
[last_name] => Filipe
)
[2] => Array
(
[id] => 3
[first_name] => Alice
[last_name] => Gustav
)
)
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.magic.set-state">
<title><link linkend="object.set-state">__set_state()</link></title>
<methodsynopsis xml:id="object.set-state">
<modifier>static</modifier> <type>object</type><methodname>__set_state</methodname>
<methodparam><type>array</type><parameter>properties</parameter></methodparam>
</methodsynopsis>
<para>
This <link linkend="language.oop5.static">static</link> method is called
for classes exported by <function>var_export</function>.
</para>
<para>
The only parameter of this method is an array containing exported
properties in the form <literal>['property' => value, ...]</literal>.
</para>
<example>
<title>Using <link linkend="object.set-state">__set_state()</link></title>
<programlisting role="php">
<![CDATA[
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
$b = var_export($a, true);
var_dump($b);
eval('$c = ' . $b . ';');
var_dump($c);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(60) "A::__set_state(array(
'var1' => 5,
'var2' => 'foo',
))"
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
]]>
</screen>
</example>
<note>
<simpara>
When exporting an object, <function>var_export</function> does not check
whether <link linkend="object.set-state">__set_state()</link> is
implemented by the object's class, so re-importing objects will result in an <classname>Error</classname> exception,
if __set_state() is not implemented. Particularly, this affects some
internal classes.
</simpara>
<simpara>
It is the responsibility of the programmer to verify that only objects will
be re-imported, whose class implements __set_state().
</simpara>
</note>
</sect2>
<sect2 xml:id="language.oop5.magic.debuginfo">
<title><link linkend="object.debuginfo">__debugInfo()</link></title>
<methodsynopsis xml:id="object.debuginfo">
<type>array</type><methodname>__debugInfo</methodname>
<void/>
</methodsynopsis>
<para>
This method is called by <function>var_dump</function> when dumping an
object to get the properties that should be shown. If the method isn't
defined on an object, then all public, protected and private properties
will be shown.
</para>
<example>
<title>Using <link linkend="object.debuginfo">__debugInfo()</link></title>
<programlisting role="php">
<![CDATA[
<?php
class C {
private $prop;
public function __construct($val) {
$this->prop = $val;
}
public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new C(42));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(C)#1 (1) {
["propSquared"]=>
int(1764)
}
]]>
</screen>
</example>
</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
-->
|