Php public class extends

PHP OOP — Inheritance

Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.

An inherited class is defined by using the extends keyword.

Example

class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
public function intro() echo «The fruit is name> and the color is color>.»;
>
>

// Strawberry is inherited from Fruit
class Strawberry extends Fruit public function message() echo «Am I a fruit or a berry? «;
>
>
$strawberry = new Strawberry(«Strawberry», «red»);
$strawberry->message();
$strawberry->intro();
?>

Example Explained

The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

PHP — Inheritance and the Protected Access Modifier

In the previous chapter we learned that protected properties or methods can be accessed within the class and by classes derived from that class. What does that mean?

Example

class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
protected function intro() echo «The fruit is name> and the color is color>.»;
>
>

class Strawberry extends Fruit public function message() echo «Am I a fruit or a berry? «;
>
>

// Try to call all three methods from outside class
$strawberry = new Strawberry(«Strawberry», «red»); // OK. __construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>

In the example above we see that if we try to call a protected method (intro()) from outside the class, we will receive an error. public methods will work fine!

Let’s look at another example:

Example

class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
protected function intro() echo «The fruit is name> and the color is color>.»;
>
>

class Strawberry extends Fruit public function message() echo «Am I a fruit or a berry? «;
// Call protected method from within derived class — OK
$this -> intro();
>
>

$strawberry = new Strawberry(«Strawberry», «red»); // OK. __construct() is public
$strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from within the derived class
?>

In the example above we see that all works fine! It is because we call the protected method (intro()) from inside the derived class.

PHP — Overriding Inherited Methods

Inherited methods can be overridden by redefining the methods (use the same name) in the child class.

Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):

Example

class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
public function intro() echo «The fruit is name> and the color is color>.»;
>
>

class Strawberry extends Fruit public $weight;
public function __construct($name, $color, $weight) $this->name = $name;
$this->color = $color;
$this->weight = $weight;
>
public function intro() echo «The fruit is name>, the color is color>, and the weight is weight> gram.»;
>
>

$strawberry = new Strawberry(«Strawberry», «red», 50);
$strawberry->intro();
?>

PHP — The final Keyword

The final keyword can be used to prevent class inheritance or to prevent method overriding.

The following example shows how to prevent class inheritance:

Example

// will result in error
class Strawberry extends Fruit // some code
>
?>

The following example shows how to prevent method overriding:

Example

class Fruit final public function intro() // some code
>
>

class Strawberry extends Fruit // will result in error
public function intro() // some code
>
>
?>

Источник

Php public class extends

INSIDE CODE and OUTSIDE CODE

class Item
/**
* This is INSIDE CODE because it is written INSIDE the class.
*/
public $label ;
public $price ;
>

/**
* This is OUTSIDE CODE because it is written OUTSIDE the class.
*/
$item = new Item ();
$item -> label = ‘Ink-Jet Tatoo Gun’ ;
$item -> price = 49.99 ;

?>

Ok, that’s simple enough. I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it — huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) — another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that’s it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float — which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

class Item
/**
* Here’s the new INSIDE CODE and the Rules to follow:
*
* 1. STOP ACCESS to properties via $item->label and $item->price,
* by using the protected keyword.
* 2. FORCE the use of public functions.
* 3. ONLY strings are allowed IN & OUT of this class for $label
* via the getLabel and setLabel functions.
* 4. ONLY floats are allowed IN & OUT of this class for $price
* via the getPrice and setPrice functions.
*/

protected $label = ‘Unknown Item’ ; // Rule 1 — protected.
protected $price = 0.0 ; // Rule 1 — protected.

public function getLabel () < // Rule 2 - public function.
return $this -> label ; // Rule 3 — string OUT for $label.
>

public function getPrice () < // Rule 2 - public function.
return $this -> price ; // Rule 4 — float OUT for $price.
>

public function setLabel ( $label ) // Rule 2 — public function.
/**
* Make sure $label is a PHP string that can be used in a SORTING
* alogorithm, NOT a boolean, number, array, or object that can’t
* properly sort — AND to make sure that the getLabel() function
* ALWAYS returns a genuine PHP string.
*
* Using a RegExp would improve this function, however, the main
* point is the one made above.
*/

if( is_string ( $label ))
$this -> label = (string) $label ; // Rule 3 — string IN for $label.
>
>

public function setPrice ( $price ) // Rule 2 — public function.
/**
* Make sure $price is a PHP float so that it can be used in a
* NUMERICAL CALCULATION. Do not accept boolean, string, array or
* some other object that can’t be included in a simple calculation.
* This will ensure that the getPrice() function ALWAYS returns an
* authentic, genuine, full-flavored PHP number and nothing but.
*
* Checking for positive values may improve this function,
* however, the main point is the one made above.
*/

if( is_numeric ( $price ))
$this -> price = (float) $price ; // Rule 4 — float IN for $price.
>
>
>

?>

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you. which means you can keep your hair!

If you have problems with overriding private methods in extended classes, read this:)

The manual says that «Private limits visibility only to the class that defines the item». That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the «same» private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent’s private methods. If the child doesn’t see the parent’s private methods, the child can’t override them. Scopes are different. In other words — each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

abstract class base <
public function inherited () <
$this -> overridden ();
>
private function overridden () <
echo ‘base’ ;
>
>

class child extends base <
private function overridden () <
echo ‘child’ ;
>
>

$test = new child ();
$test -> inherited ();
?>

Output will be «base».

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That’s what it is for:)

A sample that works as intended:

abstract class base <
public function inherited () <
$this -> overridden ();
>
protected function overridden () <
echo ‘base’ ;
>
>

class child extends base <
protected function overridden () <
echo ‘child’ ;
>
>

$test = new child ();
$test -> inherited ();
?>
Output will be «child».

Источник

Наследование классов

Представьте, что у вас есть класс User . Он нужен вам для каких-то целей и в общем-то полностью вас устраивает — доработки этому классу в не нужны.

А теперь представим себе ситуацию, когда нам понадобился еще и класс Employee . Работник очень похож на юзера, имеет те же свойства и методы, но еще и добавляет свои — свойство salary , а также геттер и сеттер для этого свойства. Вот этот класс:

salary; > // Сеттер зарплаты public function setSalary($salary) < $this->salary = $salary; > public function getName() < return $this->age; > public function setName($name) < $this->name = $name; > public function getAge() < return $this->age; > public function setAge($age) < $this->age = $age; > > ?>

Как мы видим, код классов User и Employee практически полностью совпадает. Было бы намного лучше сделать так, чтобы общая часть была записана только в одном месте.

Для решения проблемы существует такая вещь, как . С помощью наследования мы можем заставить наш класс Employee позаимствовать () методы и свойства класса User и просто дополнить их своими методами и свойствами.

Класс, от которого наследуют называется ( англ. parent ), а класс, который наследует — . Класс-потомок наследует только публичные методы и свойства, но не приватные.

Наследование реализуется с помощью ключевого слова extends (переводится как расширяет ). Перепишем наш класс Employee так, чтобы он наследовал от User :

Проверим работу нового класса Employee :

setSalary(1000); // метод класса Employee $employee->setName(‘john’); // метод унаследован от родителя $employee->setAge(25); // метод унаследован от родителя echo $employee->getSalary(); // метод класса Employee echo $employee->getName(); // метод унаследован от родителя echo $employee->getAge(); // метод унаследован от родителя ?>

Класс-потомок не унаследовал от своего родителя приватные свойства name и age — попытка обратится к ним вызовет ошибку. При этом, однако, в классе-потомке доступны геттеры и сеттеры этих свойств, так как эти геттеры и сеттеры являются публичными.

Не подсматривая в мой код реализуйте такие же классы User , Employee .

Несколько потомков

Преимущества наследования в том, что каждый класс может несколько потомков. Давайте посмотрим на примере. Пусть кроме работника нам нужен еще и класс Student — давайте также унаследуем его от User :

Проверим работу нашего класса:

setCourse(3); // метод класса Student $student->setName(‘john’); // метод унаследован от родителя $student->setAge(25); // метод унаследован от родителя echo $student->getCourse(); // метод класса Student echo $student->getName(); // метод унаследован от родителя echo $student->getAge(); // метод унаследован от родителя ?>

Не подсматривая в мой код реализуйте такой же класс Student , наследующий от класса User .

Наследование от наследников

Пусть у нас есть класс-родитель и класс-потомок. От этого потомка также могут наследовать другие классы, от его потомков другие и так далее. Для примера пусть от класса User наследует Student , а от него в свою очередь наследует класс StudentBSU :

Сделайте класс Programmer , который будет наследовать от класса Employee . Пусть новый класс имеет свойство langs , в котором будет хранится массив языков, которыми владеет программист. Сделайте также геттер и сеттер для этого свойства.

Сделайте класс Driver ( водитель ), который будет наследовать от класса Employee . Пусть новый класс добавляет следующие свойства: водительский стаж, категория вождения (A, B, C, D), а также геттеры и сеттеры к ним.

Источник

Читайте также:  Python for statistics pdf
Оцените статью