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
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.traits" xmlns="http://docbook.org/ns/docbook">
<title>Traits</title>
<para>
PHP implements a way to reuse code called Traits.
</para>
<para>
Traits are a mechanism for code reuse in single inheritance languages such as
PHP. A Trait is intended to reduce some limitations of single inheritance by
enabling a developer to reuse sets of methods freely in several independent
classes living in different class hierarchies. The semantics of the combination
of Traits and classes is defined in a way which reduces complexity, and avoids
the typical problems associated with multiple inheritance and Mixins.
</para>
<para>
A Trait is similar to a class, but only intended to group functionality in a
fine-grained and consistent way. It is not possible to instantiate a Trait on
its own. It is an addition to traditional inheritance and enables horizontal
composition of behavior; that is, the application of class members without
requiring inheritance.
</para>
<example xml:id="language.oop5.traits.basicexample">
<title>Trait example</title>
<programlisting role="php">
<![CDATA[
<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>
]]>
</programlisting>
</example>
<sect2 xml:id="language.oop5.traits.precedence">
<title>Precedence</title>
<para>
An inherited member from a base class is overridden by a member inserted
by a Trait. The precedence order is that members from the current class
override Trait methods, which in turn override inherited methods.
</para>
<example xml:id="language.oop5.traits.precedence.examples.ex1">
<title>Precedence Order Example</title>
<para>
An inherited method from a base class is overridden by the
method inserted into MyHelloWorld from the SayWorld Trait. The behavior is
the same for methods defined in the MyHelloWorld class. The precedence order
is that methods from the current class override Trait methods, which in
turn override methods from the base class.
</para>
<programlisting role="php">
<![CDATA[
<?php
class Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
<example xml:id="language.oop5.traits.precedence.examples.ex2">
<title>Alternate Precedence Order Example</title>
<programlisting role="php">
<![CDATA[
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo 'Hello Universe!';
}
}
$o = new TheWorldIsNotEnough();
$o->sayHello();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello Universe!
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.multiple">
<title>Multiple Traits</title>
<para>
Multiple Traits can be inserted into a class by listing them in the <literal>use</literal>
statement, separated by commas.
</para>
<example xml:id="language.oop5.traits.multiple.ex1">
<title>Multiple Traits Usage</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.conflict">
<title>Conflict Resolution</title>
<para>
If two Traits insert a method with the same name, a fatal error is produced,
if the conflict is not explicitly resolved.
</para>
<para>
To resolve naming conflicts between Traits used in the same class,
the <literal>insteadof</literal> operator needs to be used to choose exactly
one of the conflicting methods.
</para>
<para>
Since this only allows one to exclude methods, the <literal>as</literal>
operator can be used to add an alias to one of the methods. Note the
<literal>as</literal> operator does not rename the method and it does not
affect any other method either.
</para>
<example xml:id="language.oop5.traits.conflict.ex1">
<title>Conflict Resolution</title>
<para>
In this example, Talker uses the traits A and B.
Since A and B have conflicting methods, it defines to use
the variant of smallTalk from trait B, and the variant of bigTalk from
trait A.
</para>
<para>
The Aliased_Talker makes use of the <literal>as</literal> operator
to be able to use B's bigTalk implementation under an additional alias
<literal>talk</literal>.
</para>
<programlisting role="php">
<![CDATA[
<?php
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.visibility">
<title>Changing Method Visibility</title>
<para>
Using the <literal>as</literal> syntax, one can also adjust the visibility
of the method in the exhibiting class.
</para>
<example xml:id="language.oop5.traits.visibility.ex1">
<title>Changing Method Visibility</title>
<programlisting role="php">
<![CDATA[
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
// Change visibility of sayHello
class MyClass1 {
use HelloWorld { sayHello as protected; }
}
// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
use HelloWorld { sayHello as private myPrivateHello; }
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.composition">
<title>Traits Composed from Traits</title>
<para>
Just as classes can make use of traits, so can other traits. By using one
or more traits in a trait definition, it can be composed partially or
entirely of the members defined in those other traits.
</para>
<example xml:id="language.oop5.traits.composition.ex1">
<title>Traits Composed from Traits</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World!';
}
}
trait HelloWorld {
use Hello, World;
}
class MyHelloWorld {
use HelloWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.abstract">
<title>Abstract Trait Members</title>
<para>
Traits support the use of abstract methods in order to impose requirements
upon the exhibiting class. Public, protected, and private methods are supported.
Prior to PHP 8.0.0, only public and protected abstract methods were supported.
</para>
<caution>
<simpara>
As of PHP 8.0.0, the signature of a concrete method must follow the
<link linkend="language.oop.lsp">signature compatibility rules</link>.
Previously, its signature might be different.
</simpara>
</caution>
<example xml:id="language.oop5.traits.abstract.ex1">
<title>Express Requirements by Abstract Methods</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHelloWorld() {
echo 'Hello'.$this->getWorld();
}
abstract public function getWorld();
}
class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.static">
<title>Static Trait Members</title>
<para>
Traits can define static variables, static methods and static properties.
</para>
<note>
<para>
As of PHP 8.1.0, calling a static method, or accessing a static property directly on a trait is deprecated.
Static methods and properties should only be accessed on a class using the trait.
</para>
</note>
<example xml:id="language.oop5.traits.static.ex1">
<title>Static Variables</title>
<programlisting role="php">
<![CDATA[
<?php
trait Counter {
public function inc() {
static $c = 0;
$c = $c + 1;
echo "$c\n";
}
}
class C1 {
use Counter;
}
class C2 {
use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.traits.static.ex2">
<title>Static Methods</title>
<programlisting role="php">
<![CDATA[
<?php
trait StaticExample {
public static function doSomething() {
return 'Doing something';
}
}
class Example {
use StaticExample;
}
Example::doSomething();
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.traits.static.ex3">
<title>Static Properties</title>
<caution>
<simpara>
Prior to PHP 8.3.0, static properties were shared across all classes
using the trait. As of PHP 8.3.0, each class using the trait has its
own copy of the static property.
</simpara>
</caution>
<programlisting role="php">
<![CDATA[
<?php
trait StaticExample {
public static $static = 'foo';
}
class Example {
use StaticExample;
}
echo Example::$static;
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.properties">
<title>Properties</title>
<para>
Traits can also define properties.
</para>
<example xml:id="language.oop5.traits.properties.example">
<title>Defining Properties</title>
<programlisting role="php">
<![CDATA[
<?php
trait PropertiesTrait {
public $x = 1;
}
class PropertiesExample {
use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>
]]>
</programlisting>
</example>
<para>
If a trait defines a property then a class can not define a property with
the same name unless it is compatible (same visibility and type,
readonly modifier, and initial value), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.properties.conflicts">
<title>Conflict Resolution</title>
<programlisting role="php">
<![CDATA[
<?php
trait PropertiesTrait {
public $same = true;
public $different1 = false;
public bool $different2;
public bool $different3;
}
class PropertiesExample {
use PropertiesTrait;
public $same = true;
public $different1 = true; // Fatal error
public string $different2; // Fatal error
readonly protected bool $different3; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.constants">
<title>&Constants;</title>
<para>
Traits can, as of PHP 8.2.0, also define constants.
</para>
<example xml:id="language.oop5.traits.constants.example">
<title>Defining Constants</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
}
$example = new ConstantsExample;
echo $example::FLAG_MUTABLE; // 1
?>
]]>
</programlisting>
</example>
<para>
If a trait defines a constant then a class can not define a constant with
the same name unless it is compatible (same visibility, initial value, and
finality), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.constants.conflicts">
<title>Conflict Resolution</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
public const FLAG_IMMUTABLE = 5; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.final-methods">
<title>Final methods</title>
<simpara>
As of PHP 8.3.0, the <link linkend="language.oop5.final">final</link>
modifier can be applied to methods coming from traits.
</simpara>
<example xml:id="language.oop5.traits.final-methods.example">
<title>Defining a method coming from a trait as <literal>final</literal></title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public function method() {
echo 'Hello';
}
}
class ConstantsExample {
use ConstantsTrait;
final public function method() {
echo 'Hello World';
}
}
?>
]]>
</programlisting>
</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
-->
|