Real World Examples of Advanced OOP Features for PHP

I am trying to improve my knowledge of OOP in PHP and learn abstract classes and interfaces.

What i learned

  • These are both classes that cannot be created by themselves, but can be extended (implemented in the case of interfaces).
  • Abstract classes provide methods and properties for other classes that extend them.
  • If a class uses an abstract method, the class itself must also be abstract.
  • If an abstract method is defined in an abstract class, all child classes must define the details of this method. Methods not defined as abstract can be used in the same way as conventional methods.
  • Interfaces determine what methods the class that implements it must execute. The functionality of the methods is not defined in the interface; the interface simply offers a list of methods that should be included in the child class.
  • The interface does not define any properties.
  • Classes can implement as many interfaces as they want, but they must define a method for each of the interfaces that they implement.

I think it covers the basics. Feel free to add to this if you think I haven't missed anything.

, , - , . - - , , , , ? , , .

+5
5

, , , Command Pattern. . , , .

, " " OO, , .

public function fn(ConcreteClass $obj)
{
    $obj->doSomething()
}

,

public function fn(MyInterface $obj)
{
    $obj->doSomething()
}

. PHP Single Inheritance, :

BaseClass -> Logger -> Auth -> User

, .

User implements Loggable, Authenticable

/, .

PHP . :

+1

, :

class Parent
{
}

class Mother extends Parent
{
}

final class Brother extends Mother /* - This class cannot be extended - */
{
}

class Pet extends Brother
{
}

Pet : Fatal error: Class Pet may not inherit from final class (Brother)

, , , , , .

http://php.net/manual/en/language.oop5.final.php

, , ,

1 , , , MySql, MsSql .., class, , , , .

interface IDatabaseLayer
{
    public function connect();
    public function query();
    public function sanitize();
    //...
}

, , MySql MsSql , .

, , PHP5 , .

, 3

  • DatabaseCredentials
  • DatabaseConnection
  • DatabaseQuery

DatabaseConnection, DatabaseCredentials:

class DatabaseConnection implements Connectable
{
    public function __construct(DatabaseCredentials $ConnectionDetails)
    {
        $this->Connect($ConnectionDetails->BuildDSN());
    }
}

- :


PHP5, , , , - , , , .

:

namespace Database\MySql
{
    class Database{}
}

namespace Database\MsSql
{
    class Database{}
}

:

use Database;
$Database = new MySql\Database();
+1

" PHP" dzone , , .

PHP stackoverflow, PHP.

+1

We can say that the interface is a purely 100% abstract class, but it is not abstract. Because many times we define a function in an abstract class. But in an interface class, we always declare a function.

0
source

All Articles