Зачем нужны абстрактные классы php

Зачем нужны абстрактные классы php

Абстрактный класс представляет частичную реализацию для классов-наследников.

Абстрактный класс определяется с помощью модификатора abstract , который ставится перед именем класса:

Одной из ключевых особенностей абстрактных классов является то, что мы не можем напрямую создать объекты абстрактного класса с помощью вызова его конструктора:

abstract class Messenger < >$telegram = new Messenger(); // эта строка не будет работать

Абстрактные классы, как и обычные классы, могут определять переменные и константы, методы и конструкторы.

Но другой особенностью абстрактных классов является то, что они могут содержать абстрактные методы. Это методы, которые не имеют реализации. Реализацию для них предоставляют классы-наследники. Например:

При определении абстрактного метода перед словом function ставится модификатор abstract . А после списка параметров метода — точка с запятой.

Абстрактные методы могут размещаться только в абстрактных классах. Обычный неабстрактный класс не может иметь абстрактных методов.

Если неабстрактный класс наследуется от абстрактного класса, то он обязан реализовать все его абстрактные методы.

Для наследования классом абстрактного класса, как и в общем случае при наследовании, применяется ключевое слово extends . Например:

name = $name; > abstract function send($message); function close() < echo "Выход из мессенджера. "; >> class EmailMessenger extends Messenger < function send($message) < echo "$this->name отправляет сообщение: $message
"; > > $outlook = new EmailMessenger("Outlook"); $outlook->send("Hello PHP 8"); $outlook -> close(); ?> ?>

В данном случае класс EmailMessenger наследуется от абстрактного класса Messenger.

Абстрактный класс определяет абстрактный метод send() , поэтому класс-наследник EmailMessenger должен предоставить реализацию для этого метода.

Так, в данном случае мы получим следующий вывод:

Outlook отправляет сообщение: Hello PHP 8 Выход из мессенджера.

Можно заметить, что абстрактные классы похожи на интерфейсы — и те, и другие могут определять методы без реализации, которые реализуются в других классах. Однако, абстрактные классы, как и обычные классы, могут иметь переменные, неабстрактные методы, конструкторы с реализацией, а интерфейсы нет. Кроме того, в PHP один класс может наследоваться только от одного класса, тогда как один класс может применять сразу несколько интерфейсов.

Источник

Зачем нужны абстрактные классы php

This example will hopefully help you see how abstract works, how interfaces work, and how they can work together. This example will also work/compile on PHP7, the others were typed live in the form and may work but the last one was made/tested for real:

// Define things a product *has* to be able to do (has to implement)
interface productInterface public function doSell ();
public function doBuy ();
>

// Define our default abstraction
abstract class defaultProductAbstraction implements productInterface private $_bought = false ;
private $_sold = false ;
abstract public function doMore ();
public function doSell () /* the default implementation */
$this -> _sold = true ;
echo «defaultProductAbstraction doSell: < $this ->_sold > » . ¶ ;
>
public function doBuy () $this -> _bought = true ;
echo «defaultProductAbstraction doBuy: < $this ->_bought > » . ¶ ;
>
>

class defaultProductImplementation extends defaultProductAbstraction public function doMore () echo «defaultProductImplementation doMore()» . ¶ ;
>
>

class myProductImplementation extends defaultProductAbstraction public function doMore () echo «myProductImplementation doMore() does more!» . ¶ ;
>
public function doBuy () echo «myProductImplementation’s doBuy() and also my parent’s dubai()» . ¶ ;
parent :: doBuy ();
>
>

class myProduct extends defaultProductImplementation private $_bought = true ;
public function __construct () var_dump ( $this -> _bought );
>
public function doBuy () /* non-default doBuy implementation */
$this -> _bought = true ;
echo «myProduct overrides the defaultProductImplementation’s doBuy() here < $this ->_bought > » . ¶ ;
>
>

class myOtherProduct extends myProductImplementation public function doBuy () echo «myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too» . ¶ ;
parent :: doBuy ();
>
>

echo «new myProduct()» . ¶ ;
$product = new myProduct ();

$product -> doBuy ();
$product -> doSell ();
$product -> doMore ();

echo ¶ . «new defaultProductImplementation()» . ¶ ;

$newProduct = new defaultProductImplementation ();
$newProduct -> doBuy ();
$newProduct -> doSell ();
$newProduct -> doMore ();

echo ¶ . «new myProductImplementation» . ¶ ;
$lastProduct = new myProductImplementation ();
$lastProduct -> doBuy ();
$lastProduct -> doSell ();
$lastProduct -> doMore ();

echo ¶ . «new myOtherProduct» . ¶ ;
$anotherNewProduct = new myOtherProduct ();
$anotherNewProduct -> doBuy ();
$anotherNewProduct -> doSell ();
$anotherNewProduct -> doMore ();
?>

Will result in:
/*
new myProduct()
bool(true)
myProduct overrides the defaultProductImplementation’s doBuy() here 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new defaultProductImplementation()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new myProductImplementation
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

new myOtherProduct
myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

Also you may set return/arguments type declaring for abstract methods (PHP>=7.0)
declare( strict_types = 1 );

abstract class Adapter
protected $name ;
abstract public function getName (): string ;
abstract public function setName ( string $value );
>

class AdapterFoo extends Adapter
public function getName (): string
return $this -> name ;
>
// return type declaring not defined in abstract class, set here
public function setName ( string $value ): self
$this -> name = $value ;
return $this ;
>
>
?>

The documentation says: «It is not allowed to create an instance of a class that has been defined as abstract.». It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
abstract class Foo
static function bar ()
echo «test\n» ;
>
>

Here is another thing about abstract class and interface.

Sometimes, we define an interface for a `Factory` and ease out some common methods of the `Factory` through an `abstract` class.

In this case, the abstract class implements the interface, but does not need to implement all methods of the interface.

The simple reason is, any class implementing an interface, needs to either implement all methods, or declare itself abstract.

Because of this, the following code is perfectly ok.

interface Element /**
* Constructor function. Must pass existing config, or leave as
* is for new element, where the default will be used instead.
*
* @param array $config Element configuration.
*/
public function __construct ( $config = [] );

/**
* Get the definition of the Element.
*
* @return array An array with ‘title’, ‘description’ and ‘type’
*/
public static function get_definition ();

/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config ();

/**
* Set Element config variable.
*
* @param array $config New configuration variable.
*
* @return void
*/
public function set_config ( $config );
>

abstract class Base implements Element

/**
* Element configuration variable
*
* @var array
*/
protected $config = [];

/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config () return $this -> config ;
>

/**
* Create an eForm Element instance
*
* @param array $config Element config.
*/
public function __construct ( $config = [] ) $this -> set_config ( $config );
>
>

class MyElement extends Base

public static function get_definition () return [
‘type’ => ‘MyElement’ ,
];
>

public function set_config ( $config ) // Do something here
$this -> config = $config ;
>
>

$element = new MyElement ( [
‘foo’ => ‘bar’ ,
] );

print_r ( $element -> get_config () );
?>

You can see the tests being executed here and PHP 5.4 upward, the output is consistent. https://3v4l.org/8NqqW

Ok. the docs are a bit vague when it comes to an abstract class extending another abstract class. An abstract class that extends another abstract class doesn’t need to define the abstract methods from the parent class. In other words, this causes an error:

abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
abstract public function someFunc ();
>
?>

Error: Fatal error: Can’t inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7

abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
>
?>

An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.

An interface specifies what methods a class must implement, so that anything using that class that expects it to adhere to that interface will work.

eg: I expect any $database to have ->doQuery(), so any class I assign to the database interface should implement the databaseInterface interface which forces implementation of a doQuery method.

interface dbInterface public function doQuery ();
>

class myDB implements dbInterface public function doQuery () /* implementation details here */
>
>

$myDBObj = new myDB ()-> doQuery ();
?>

An abstract class is similar except that some methods can be predefined. Ones listed as abstract will have to be defined as if the abstract class were an interface.

eg. I expect my $person to be able to ->doWalk(), most people walk fine with two feet, but some people have to hop along 🙁

interface PersonInterface () /* every person should walk, or attempt to */
public function doWalk ( $place );
/* every person should be able to age */
public function doAge ();
>

abstract class AveragePerson implements PersonInterface () private $_age = 0 ;
public function doAge () $this -> _age = $this -> _age + 1 ;
>
public function doWalk ( $place ) echo «I am going to walk to $place » . PHP_EOL ;
>
/* every person talks differently! */
abstract function talk ( $say );
>

class Joe extends AveragePerson public function talk ( $say ) echo «In an Austrailian accent, Joe says: $say » . PHP_EOL ;
>
>

class Bob extends AveragePerson public function talk ( $say ) echo «In a Canadian accent, Bob says: $say » . PHP_EOL ;
>
public function doWalk ( $place ) echo «Bob only has one leg and has to hop to $place » . PHP_EOL ;
>
>

$people [] = new Bob ();
$people [] = new Joe ();

foreach ( $people as $person ) $person -> doWalk ( ‘over there’ );
$person -> talk ( ‘PHP rules’ );
>
?>

Источник

Читайте также:  Java developers in poland
Оцените статью