First, the concept of object-oriented

1.1 What is Object Orientation (object oriented)

Everything in the world is an object, the abstract is an object, everything visible or invisible is an object

1.2 Basic Composition of objects

The object contains two parts:

  • The constituent elements of the object

    • Is the object’sThe data modelIs used to describe the data of an object

      Also known as objectattributeOr of the objectMember variables
  • Behavior of objects

    • Is the object’sBehavioral modelIs used to describe what an object can do

      Also known as objectmethods

1.3 Object Features

  • Each object is unique
  • An object is a specific thing whose function is to perform a specific function
  • Objects are reusable

1.4 Introduction to Object Orientation

  1. Object-oriented programming is programming in which data structures (how data is organized) are stored in object structures, organized using properties and methods
  2. Why use object-oriented programming? Objects are described in a way that more closely matches the real world, facilitating understanding of large businesses

1.5 The essence of object orientation

  1. Object oriented is to solve the problems in life are stored in the way of objects — all the data with attributes, methods.
  2. Objects interact with each other through method calls

1.6 Basic idea of object-oriented

  1. Identification Object Any entity can be identified as an object
  2. Identify object properties The data stored in objects are identified as properties. For different business logic, different data is concerned with and different properties are stored in objects
  3. Identifying the behavior of an object the change of its own property data the interaction outside the object

1.7 Basic object-oriented principles

  1. objectinternalHigh cohesion

    The object is only responsible for one itemSpecific functions(Function may be large or small)

    All object-related content is encapsulated inside the object
  2. objectexternalLow coupling

    The outside world can see some (but not all) properties of the object

    The outside world can see that objects can do some things (not all of them)

Software design should be as cohesive as possible, with low coupling, and modules should be independent of each other without dependencies

Two, the basic practice of object oriented

2.1 Concept of classes

  1. Birds of a feather flock together, matching objects with similar properties into a class
  2. Class defines the same properties and methods that these similar objects have
  3. A class is a description of similar objects, which becomes the definition of the class, and is the blueprint or prototype of the class objects
  4. An object of a class is called a classThe instance(Instance)
  5. The properties and methods of a class are collectively calledMembers of the class

2.2 Instantiation of classes

  • Class instantiation: Create an object of a class through a class definition
  • Class definition property values are empty or default values, whereas object properties have specific values

2.3 Definition of class

  1. Classes are defined by keywordsclassStart, followed by the class name. The class nameUsually the first letter of each word is capitalized, begins and ends with brackets
  2. Classes are instantiated as objects using keywordsnew.newThis is followed by the name of the class and a pair of parentheses
  3. Object member properties and methods can pass->Symbol to access

2.4 Constructors

  1. The default constructor is called automatically when the object is instantiated
  2. $thisisPhpThe inside of theDummy variablesRepresents the object itself. Can be achieved by$this->To access the properties and methods of an object
  3. Every timenewWhenever an object is instantiated, the constructor is called with the argument list following the class name
  4. phpConstructor of a class functionfunction __construct(){}Automatically called at runtime

2.5 Destructors

  1. function __destruct(){}Destructors are based on last in, first out
  2. There areOne of two waysThe destructor is executed: the object is not setnullOr when the program ends, the destructor will be automatically called, and the occupied resources are recycled by the system
  3. Destructors are typically used to clean up resources used by programs, such as freeing open files, and so on
  4. The destructor is called automatically if the object is no longer in use, and is not called if it is copied instead of an & reference

2.6 object&Basic concepts of reference

$james1 = $james; $james2 = &$James; // It's like giving James an alias. The two are actually one and the same, but with two namesCopy the code

Special attention:

  1. PHP always passes objects by reference(ArrayObjectIs aSPLobject, which mimics array usage, but works as objects.)
  2. $arr = array(); $arr2 = $arr; $arr2is$arrA copy of the array, they do not affect each other and are independent arrays
  3. &Objects (arrays) are all equivalentThe alias

Deeper understanding of PHP references:Common mistake #3: Confusion about returning by reference versus returning by value

Third, object-oriented advanced combat

3.1 Object inheritance

Parent class: has some of the same properties and methods

Benefits of inheritance

  1. Class members defined in the parent class do not need to be defined repeatedly in the subclass, saving programming time and cost
  2. Subclasses of the same parent class have the same class members defined by the parent class, so they can be called equally by external code
  3. Subclasses can modify and call class members defined by the parent class

    • We calledrewrite(Overwrite)
    • Once a subclass has modified it, it does what the subclass modified it to do

The subclass:

  1. A subclass can pass$thisAccess the properties of the parent class
  2. Subclass objects can call methods and properties of their parent class directly
  3. PHPtheSingle inheritance property: classes are not allowed to inherit from more than one parent class (extendsCan only be followed by one parent name.

3.2 Access Control

There are three kinds of object-oriented access rights:

  1. Public is a public class member that can be accessed anywhere

    • Can be accessed by classes as well as subclasses or objects
  2. Protected Class members that can be accessed by themselves and by inheriting subclasses

    • It can be inherited by subclasses, but cannot be accessed by objects, only by encapsulation
  3. Private A private class member that can only be accessed by itself

    • Cannot be inherited by subclasses or accessed by objects, but can only be accessed by the outside world through encapsulation (for example, by defining a public method within a class to call a private property).

3.3 Static Keyword

Static member: add static keyword after access control keyword (access control keyword: public.protected. Private)

  1. Static attributes are used to hold the public data of a class and can be shared between different objects
  2. Only static properties can be accessed in static methods
  3. Static members can be accessed without instantiating the object
  4. The inside of the class can passself::static::Keyword to access its own static member,self::$Attribute self:: method ()
  5. throughparent::Keyword accessStatic member of the parent class, can also be static members by subclass :: parent class
  6. throughThe name of the class: :Access static members outside the class

3.4 Rewrite and Final keywords

  1. Subclass writing exactly the same as the parent class method can complete the parent class method rewrite, method parameters should have default parameters
  2. Classes that do not want to be inherited by any class can be found inclassBefore you addfinalThe keyword
  3. For those who do not want to be overridden by subclasses (overwrite, modify), which can be added before the method definitionfinalThe keyword

3.5 Data Access

  1. parentThe keyword can be used to call methods in a parent class that have been overridden by subclasses
  2. selfThe keyword can be used to access the class’s ownMembers of the method, static members and class constants;Cannot be used to access properties of the class itself!!You don’t need constants to use constantsconstAdd before name$symbol
  3. static::The keyword is used to access static members defined by the class itself. Static attributes need to be added before the attributes$Symbols.
  4. Constant propertiesconstCan’t use object access, can only use class access, inside the class body can use”The self: : constant names“, can be used outside the class ontology.Class name :: Constant name

3.6 Object Interfaces

Interfaces define the common behavior of different classes, and then implement different functions in different classes

  1. interfaceDefine the interface,implementsUsed to indicate that a class implements an interface
  2. Methods in the interface have no concrete implementation, none{}
  3. Classes that implement an interface must provide concrete implementations of methods defined in the interface
  4. You cannot instantiate an interface, but you can determine whether an object implements an interface.instanceofKeyword Determines whether an object implements an interface$object instanceof interface
  5. Interfaces can inherit from interfaces (interface extends interface)
  6. It is a feature of the interface that all methods defined in the interface must be public

3.7 polymorphic

Because interface methods can be implemented in many ways, the specific implementation of the methods defined in the interface is varied, and this property is called polymorphism

You don’t need to know which class the object belongs to, just determine whether the class of the object implements the interface, you can implement the call, the same code to achieve different results

Image point is the same interface, different object implementation, the result is not the same is polymorphic, such as the human object is introduced, get is the human eat apple, the monkey object is introduced, get is the monkey eat banana. The same line of code behaves differently for objects passed in implementations of different interfaces.

Public function eat($food); /** * $food; /** * $food; Public function eat($food){echo "Human "($food){echo "Human" ($food) eating " . $food . "\n"; Public function eat($food){echo "Animal eating ". $food.  "\n"; } } function eat($obj){ if($obj instanceof ICanEat){ $obj->eat("FOOD"); }else{echo "Can't eat! \n"; } } $man = new Human(); $monkey = new Animal(); // The same code behaves differently when passed to different implementation classes of the interface. That's why it's called polymorphism. eat($man); eat($monkey);Copy the code

3.8 the abstract class

Methods in interfaces are unimplemented, while methods in classes are implemented. Is there a form that allows some methods in a class not to be implemented?

  • When some methods in an interface are the same implementation method for all implementation classes, only some methods need to use the polymorphic property

    • For example, eating is different for humans and animals, but breathing is the same, there is no need for humans and animals to achieve the function of breathing respectively
  1. abstractThe keyword is used to define abstract classes
  2. Before the abstract methodabstractThe keyword indicates that the method is abstract and does not require a concrete implementation{}
  3. Abstract classes can contain ordinary methods, with concrete implementations of the methods
  4. The key for inheriting an abstract class isextends
  5. Subclasses that inherit from abstract classes need to implement abstract methods defined in the abstract class
  6. Abstract classes cannot be instantiated. When a subclass inherits an abstract class, all the abstract methods must be defined
/** * abstract class * 1. Abstract classes allow some methods in a class to be temporarily unimplemented. These methods are called abstract methods * 2. Once a class has abstract methods in it, the class must be abstract * 3. Abstract class ACanEat {// Unimplemented methods need to be set to abstract methods. // Abstract methods need to implement abstract public in subclasses function eat($food); public function breath(){ echo "Breath use the air.\n"; Public function eat($food){echo "Human "{$food} public function eat($food){echo "Human" eating " . $food . "\n"; Public function eat($food){echo "Animal eating ". $food. $food. "\n"; } } $man = new Human(); $man->eat("Apple"); $man->breath(); $monkey = new Animal(); $monkey = new Animal(); $monkey->eat("Banana"); $monkey->breath();Copy the code

Fourth, PHP object-oriented special practice

4.1 Magic methods _toString() and invoke()

  1. __toString()This method is called automatically when an object is used as a String (it needs to be defined in the class)__tostring()Methods. Call echo $object
  2. __invoke()When an object is called as a method, the method is automatically called (it needs to be defined in the class)__invoke()Methods). Call $object ($parameter)
/** * magic method 1 * 1. When an object is used as a String, __toString() is called automatically * 2. Class MagicTest{public function __toString(){return "This is the class magictest.\ n"; } public function __invoke($x){ echo "__invoke called with parameter " . $x . "\n"; } } $obj = new MagicTest(); echo $obj; $obj(5);Copy the code

4.2 Magic methods __call() and __callStatic()

  1. __call() method: This method is called automatically when an object accesses a nonexistent method name.

    • Call example:public function __call($name,$argument){}
    • Note: The access control keyword must bepublic; You must take two arguments: the name of the method the object accesses ($name), the parameters contained in the method ($argument==> automatically converted to array).
  2. __callStatic() method: This method is called automatically when an object accesses a nonexistent static method name.

    • Call example:public static function __callStatic($name,$argument){}
    • Note: the same__call(); This method is static.
  3. These two methods are also known as overloading methods

    • Note the distinction between rewriting (overwrite)
    • With these two methods, the invocation of the same method can correspond to different method implementations (static and dynamic invocation of the same method correspond to different method implementations).
/** * magic method method overloading * 1. The __call() method is automatically called when an object accesses a nonexistent method name * 2. When an object accesses a static method name that does not exist, */ class MagicTest{/** * automatically converts arguments to arrays * array (size=2) * 0 => string 'para1' (length=5) * 1 => string 'para2' (length=5) * @param $name * @param $arguments */ public function __call($name, $arguments){ var_dump($arguments); echo "Calling " . $name . " with parameters: " . implode(', ', $arguments) . "\n"; } public static function __callStatic($name, $arguments){ echo "Static calling " . $name . " with parameters: " . implode(', ', $arguments) . "\n"; } } $obj = new MagicTest(); $obj->runTest("para1", "para2"); MagicTest::runTest("para3","para4");Copy the code

4.3 Magic methods __get(), __set(), __isset() and __unset()

  1. In give inaccessibleattributeThe assignment,__set()Definition will be calledfunction __set($name,$value)
  2. readWhen the value of the property is not accessible,__get()Definition will be calledfunction __get($name)
  3. When called on an unreachable propertyisset()orempty()When,__isset()Is called
  4. When called on an unreachable propertyunset()When,__unset()Is called

These methods are also known as attribute overloading magic methods called inaccessible properties, which is essentially when you call a property and find that the property is not defined, different operations will trigger different magic methods

4.4 Magic Method __clone()

$obj1 = $ojb; $obj1 = clone $obj; // Implement object copy to become two objects with the same valueCopy the code

The __clone() method is automatically called when clone is called

$james = new NbaPlayer(); $James = clone $James; $James = clone $James; // Use the clone keyword when you want to generate a truly independent NbaPlayer() object, but all the data in the new object is the same as in the $James objectCopy the code

When the clone keyword is used after the __clone() method is defined in class NbaPlayer(), the system calls the user-defined __clone() method.

Finished!

Reference tutorial: OBJECT-ORIENTED programming in PHP