Рубрики
Uncategorized

Простой пример использования наследования в объектно-ориентированном программировании PHP

Автор оригинала: David Wong.

Эта статья иллюстрирует использование наследования объектно-ориентированного программирования PHP. Поделитесь для вашей справки следующим образом:

php
// Inheritance is the inheritance of attributes and methods from the parent class (base class, superclass).
// Subclasses can also have their own attributes and methods.
// A parent class can be inherited by multiple subclasses.
// If you want to modify the method of the parent class, you can only override the method in the subclass, which is also a manifestation of polymorphism.
// Use if ($obj instance of SomeClass) {} to check whether an object belongs to a class.
// If $name is protected and private access is granted, it will not be accessed directly outside the class.
// If $name is private access, it will only be accessed in its own class.
// If $name is protected access, it can be accessed either in its own class or in a subclass.
//_ construct () is the constructor of a class, which is automatically accessed when creating an object instance, and subclasses have their own constructors.
// When the subclass has no constructor, the constructor of the parent class is called when the object is created.
// When a child class has a constructor, it is not necessary to call the constructor of the parent class, unless there is an explicit call from the parent class, it is not necessary to call the constructor of the parent class.
// The destructor is called at the end of the program, or when unset () objects are used.
// If a final method is defined in a class, it will not be overridden by a subclass.
// If the class declares final, then this class cannot be inherited.
// As a rule, private variable names usually start with an underscore.
// If a class's method can only be invoked by itself, it can be set to protected or private.
// This refers to an instance of the current object, and self is used as a reference to the current class.
// Static attributes and class constants can only be accessed by class name, parent, self
// Function names are case-insensitive and variables are case-insensitive.
class Employees{
  protected $name = null;
  public static $count = 0;
  function __construct($nameStr){
    $this->name = $nameStr;
    echo "

$this->name : ",self::$count," : parent : __construct

"; } function work(){ echo "

$this->name is working

"; } function __destruct(){ echo "

parent unset $this->name

"; } } class Managers extends Employees{ private $pos = null; function __construct($p,$nameStr){ parent::$count++; parent::__construct($nameStr); $this->pos = $p; echo "

$this->name , $this->pos : self : __construct

"; } function assignJob(){ echo "

$this->name assign jobs

"; } function getName(){ return $this->name; } function __destruct(){ echo "

self unset $this->name

"; } } class Programmers extends Employees{ function code(){ echo "

$this->name is coding

"; } function getName(){ return $this->name; } } $e1 = new Employees('e1'); $e2 = new MAnagers(2,'e2'); $e3 = new Programmers('e3'); $e1->work(); $e2->work(); $e3->work(); $e2->assignJob(); $e3->Code(); echo "

{$e3->getName()}

"; //echo "

$e1->name

"; if($e2 instanceof Employees){ echo "

ok

"; }else{ echo "

no

"; } unset($e1,$e2,$e3);

Результаты операции:

e1: 0: родитель: __конструкция

e2: 1: родитель: __конструкция

e2 , 2: самость: __конструкция

e3: 1: родитель: __конструкция

e1 работает

e2 работает

e3 работает

e2 назначение заданий

e3 приближается

e3

ладно

родительский параметр не установлен e1

самоустанавливающийся e2

родитель отключил e3

Больше читателей, интересующихся контентом, связанным с PHP, могут ознакомиться с темами этого сайта: Введение в объектно-ориентированное программирование Php, Введение в навыки работы с массивами PHP, Введение в базовую грамматику PHP, Краткое описание работы с PHP и использования операторов, Краткое описание использования строк Php, Введение в работу с базой данных php+mysql и Общие операции с базами данных php. Краткое изложение навыков письма ___________

Я надеюсь, что эта статья будет полезна для разработки PHP – программ для всех.