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
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.interfaces" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Object Interfaces</title>
<para>
Object interfaces allow you to create code which specifies which methods and properties a
class must implement, without having to define how these methods or properties are
implemented. Interfaces share a namespace with classes, traits, and enumerations, so they may
not use the same name.
</para>
<para>
Interfaces are defined in the same way as a class, but with the <literal>interface</literal>
keyword replacing the <literal>class</literal> keyword and without any of the methods having
their contents defined.
</para>
<para>
All methods declared in an interface must be public; this is the nature of an
interface.
</para>
<para>
In practice, interfaces serve two complementary purposes:
</para>
<simplelist>
<member>
To allow developers to create objects of different classes that may be used interchangeably
because they implement the same interface or interfaces. A common example is multiple database access services,
multiple payment gateways, or different caching strategies. Different implementations may
be swapped out without requiring any changes to the code that uses them.
</member>
<member>
To allow a function or method to accept and operate on a parameter that conforms to an
interface, while not caring what else the object may do or how it is implemented. These interfaces
are often named like <literal>Iterable</literal>, <literal>Cacheable</literal>, <literal>Renderable</literal>,
or so on to describe the significance of the behavior.
</member>
</simplelist>
<para>
Interfaces may define
<link linkend="language.oop5.magic">magic methods</link> to require implementing classes to
implement those methods.
</para>
<note>
<para>
Although they are supported, including <link linkend="language.oop5.decon.constructor">constructors</link>
in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the
interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent
and unexpected behavior.
</para>
</note>
<sect2 xml:id="language.oop5.interfaces.implements">
<title><literal>implements</literal></title>
<para>
To implement an interface, the <literal>implements</literal> operator is used.
All methods in the interface must be implemented within a class; failure to do
so will result in a fatal error. Classes may implement more than one interface
if desired by separating each interface with a comma.
</para>
<warning>
<para>
A class that implements an interface may use a different name for its parameters than
the interface. However, as of PHP 8.0 the language supports <link linkend="functions.named-arguments">named arguments</link>, which means
callers may rely on the parameter name in the interface. For that reason, it is strongly
recommended that developers use the same parameter names as the interface being implemented.
</para>
</warning>
<note>
<para>
Interfaces can be extended like classes using the <link linkend="language.oop5.inheritance">extends</link>
operator.
</para>
</note>
<note>
<para>
The class implementing the interface must declare all methods in the interface
with a <link linkend="language.oop.lsp">compatible signature</link>. A class can implement multiple interfaces
which declare a method with the same name. In this case, the implementation must follow the
<link linkend="language.oop.lsp">signature compatibility rules</link> for all the interfaces. So
<link linkend="language.oop5.variance">covariance and contravariance</link> can be applied.
</para>
</note>
</sect2>
<!-- Move this to OOP constants page? -->
<sect2 xml:id="language.oop5.interfaces.constants">
<title>Constants</title>
<para>
It's possible for interfaces to have constants. Interface constants work exactly
like <link linkend="language.oop5.constants">class constants</link>.
Prior to PHP 8.1.0, they cannot be overridden by a class/interface that inherits them.
</para>
</sect2>
<sect2 xml:id="language.oop5.interfaces.properties">
<title>Properties</title>
<simpara>
As of PHP 8.4.0, interfaces may also declare properties.
If they do, the declaration must specify if the property is to be readable,
writeable, or both.
The interface declaration applies only to public read and write access.
</simpara>
<simpara>
An class may satisfy an interface property in multiple ways.
It may define a public property.
It may define a public
<link linkend="language.oop5.property-hooks.virtual">virtual property</link>
that implements only the corresponding hook.
Or a read property may be satisfied by a <literal>readonly</literal> property.
However, an interface property that is settable may not be <literal>readonly</literal>.
</simpara>
<example>
<title>Interface properties example</title>
<programlisting role="php">
<![CDATA[
<?php
interface I
{
// An implementing class MUST have a publicly-readable property,
// but whether or not it's publicly settable is unrestricted.
public string $readable { get; }
// An implementing class MUST have a publicly-writeable property,
// but whether or not it's publicly readable is unrestricted.
public string $writeable { set; }
// An implementing class MUST have a property that is both publicly
// readable and publicly writeable.
public string $both { get; set; }
}
// This class implements all three properties as traditional, un-hooked
// properties. That's entirely valid.
class C1 implements I
{
public string $readable;
public string $writeable;
public string $both;
}
// This class implements all three properties using just the hooks
// that are requested. This is also entirely valid.
class C2 implements I
{
private string $written = '';
private string $all = '';
// Uses only a get hook to create a virtual property.
// This satisfies the "public get" requirement.
// It is not writeable, but that is not required by the interface.
public string $readable { get => strtoupper($this->writeable); }
// The interface only requires the property be settable,
// but also including get operations is entirely valid.
// This example creates a virtual property, which is fine.
public string $writeable {
get => $this->written;
set {
$this->written = $value;
}
}
// This property requires both read and write be possible,
// so we need to either implement both, or allow it to have
// the default behavior.
public string $both {
get => $this->all;
set {
$this->all = strtoupper($value);
}
}
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.interfaces.examples">
&reftitle.examples;
<example xml:id="language.oop5.interfaces.examples.ex1">
<title>Interface example</title>
<programlisting role="php">
<![CDATA[
<?php
// Declare the interface 'Template'
interface Template
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class WorkingTemplate implements Template
{
private $vars = [];
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (Template::getHtml)
class BadTemplate implements Template
{
private $vars = [];
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.ex2">
<title>Extendable Interfaces</title>
<programlisting role="php">
<![CDATA[
<?php
interface A
{
public function foo();
}
interface B extends A
{
public function baz(Baz $baz);
}
// This will work
class C implements B
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// This will not work and result in a fatal error
class D implements B
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.variance.multiple.interfaces">
<title>Variance compatibility with multiple interfaces</title>
<programlisting role="php">
<![CDATA[
<?php
class Foo {}
class Bar extends Foo {}
interface A {
public function myfunc(Foo $arg): Foo;
}
interface B {
public function myfunc(Bar $arg): Bar;
}
class MyClass implements A, B
{
public function myfunc(Foo $arg): Bar
{
return new Bar();
}
}
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.ex3">
<title>Multiple interface inheritance</title>
<programlisting role="php">
<![CDATA[
<?php
interface A
{
public function foo();
}
interface B
{
public function bar();
}
interface C extends A, B
{
public function baz();
}
class D implements C
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.ex4">
<title>Interfaces with constants</title>
<programlisting role="php">
<![CDATA[
<?php
interface A
{
const B = 'Interface constant';
}
// Prints: Interface constant
echo A::B;
class B implements A
{
const B = 'Class constant';
}
// Prints: Class constant
// Prior to PHP 8.1.0, this will however not work because it was not
// allowed to override constants.
echo B::B;
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.ex5">
<title>Interfaces with abstract classes</title>
<programlisting role="php">
<![CDATA[
<?php
interface A
{
public function foo(string $s): string;
public function bar(int $i): int;
}
// An abstract class may implement only a portion of an interface.
// Classes that extend the abstract class must implement the rest.
abstract class B implements A
{
public function foo(string $s): string
{
return $s . PHP_EOL;
}
}
class C extends B
{
public function bar(int $i): int
{
return $i * 2;
}
}
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.interfaces.examples.ex6">
<title>Extending and implementing simultaneously</title>
<programlisting role="php">
<![CDATA[
<?php
class One
{
/* ... */
}
interface Usable
{
/* ... */
}
interface Updatable
{
/* ... */
}
// The keyword order here is important. 'extends' must come first.
class Two extends One implements Usable, Updatable
{
/* ... */
}
?>
]]>
</programlisting>
</example>
<para>
An interface, together with type declarations, provides a good way to make sure
that a particular object contains particular methods. See
<link linkend="language.operators.type">instanceof</link> operator and
<link linkend="language.types.declarations">type declarations</link>.
</para>
</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
-->
|