YouTip LogoYouTip

Php Oop

Object-Oriented (abbreviated as OO) is a programming paradigm and methodology that encapsulates data and the methods that operate on that data together within a program to form "objects," and completes the program's functionality through interaction and message passing between objects. Object-oriented programming emphasizes features such as data encapsulation, inheritance, polymorphism, and dynamic binding, making programs more extensible, maintainable, and reusable. In object-oriented programming (English: Object-oriented programming, abbreviated as OOP), an object is a whole composed of information and descriptions of how to process that information, and is an abstraction of the real world. In the real world, the things we deal with are all objects, such as computers, televisions, bicycles, etc. **The three main characteristics of objects:** * Object behavior: The operations an object can perform, for example, turning a light on or off is a behavior. * Object state: How the object responds to different behaviors, for example, color, size, shape. * Object identity: The identity of an object is like an ID card, specifically distinguishing differences under the same behavior and state. For example, Animal is an abstract class, and we can be specific to a dog and a sheep. The dog and the sheep are specific objects; they have color attributes, can write, can run, and other behavioral states. !(#) **The three main characteristics of object-oriented programming:** * Encapsulation: Refers to encapsulating the properties and methods of an object together, making it impossible for the outside world to directly access and modify the internal state of the object. Access control modifiers (public, private, protected) are used to restrict access to properties and methods, thereby achieving encapsulation. * Inheritance: Refers to the ability to create a new class that inherits the properties and methods of a parent class and can add its own properties and methods. Through inheritance, repetitive writing of similar code can be avoided, and code reuse can be achieved. * Polymorphism: Refers to the ability to use a variable of a parent class type to reference objects of different subclass types, thereby achieving unified operations on different objects. Polymorphism can make code more flexible, with better extensibility and maintainability. In PHP, polymorphism can be achieved by implementing interfaces (interface) and using abstract classes (abstract class). * * * ## Object-Oriented Content * **Class** βˆ’ Defines the abstract characteristics of a thing. The definition of a class includes the form of data and operations on that data. * **Object** βˆ’ Is an instance of a class. * **Member Variable** βˆ’ A variable defined inside a class. The value of this variable is not visible externally, but it can be accessed through member functions. After the class is instantiated into an object, this variable can become an attribute of the object. * **Member Function** βˆ’ Defined inside a class, it can be used to access the data of an object. * **Inheritance** βˆ’ Inheritance is a mechanism by which a subclass automatically shares the data structure and methods of a parent class. This is a relationship between classes. When defining and implementing a class, it can be based on an already existing class, using the content defined by this existing class as its own content and adding some new content. * **Parent Class** βˆ’ A class that is inherited by other classes can be called a parent class, or base class, or superclass. * **Child Class** βˆ’ A class that inherits from other classes is called a child class, also known as a derived class. * **Polymorphism** βˆ’ Polymorphism refers to the ability of the same function or method to act on multiple types of objects and produce different results. Different objects receiving the same message can produce different results; this phenomenon is called polymorphism. * **Overloading** βˆ’ Simply put, it is a situation where functions or methods have the same name but different parameter lists. Functions or methods with the same name but different parameters are called overloaded functions or methods. * **Abstraction** βˆ’ Abstraction refers to abstracting objects with consistent data structures (attributes) and behaviors (operations) into classes. A class is such an abstraction; it reflects important properties related to the application while ignoring other irrelevant content. Any classification of classes is subjective but must be related to the specific application. * **Encapsulation** βˆ’ Encapsulation refers to binding the attributes and behaviors of a certain object existing in the real world together and placing them within a logical unit. * **Constructor** βˆ’ Primarily used to initialize an object when it is created, that is, to assign initial values to the object's member variables. It is always used with the `new` operator in statements that create objects. * **Destructor** βˆ’ The destructor is opposite to the constructor. When an object ends its lifecycle (for example, the function where the object is located has finished executing), the system automatically executes the destructor. Destructors are often used for "cleanup" work (for example, if a memory space was allocated with `new` when the object was created, it should be released with `delete` in the destructor before exiting). In the figure below, we created three objects using the `Car` class: Mercedes, Bmw, and Audi. $mercedes = new Car (); $bmw = new Car (); $audi = new Car (); !(#) * * * ## PHP Class Definition The general syntax for defining a class in PHP is as follows: Analysis: * A class is defined using the **class** keyword followed by the class name. * Inside the pair of curly braces ({}) following the class name, variables and methods can be defined. * Class variables are declared using **var**, and variables can also be initialized with values. * Function definitions are similar to PHP function definitions, but functions can only be accessed through the class and its instantiated objects. ### Example url = $par; } function getUrl(){ echo $this->url . PHP_EOL; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title . PHP_EOL; }}?> The variable **$this** represents the object itself. **PHP_EOL** is a newline character. * * * ## Creating Objects in PHP After a class is created, we can use the **new** operator to instantiate an object of that class: $ = new Site; $taobao = new Site; $google = new Site; The above code creates three objects, each of which is independent. Next, let's see how to access member methods and member variables. ### Calling Member Methods After instantiating an object, we can use that object to call member methods. The member methods of that object can only operate on the member variables of that object: // Call member functions, set title and URL $->setTitle( "" ); $taobao->setTitle( "Taobao" ); $google->setTitle( "Google Search" ); $->setUrl( 'www.' ); $taobao->setUrl( 'www.taobao.com' ); $google->setUrl( 'www.google.com' );// Call member functions, get title and URL $->getTitle(); $taobao->getTitle(); $google->getTitle(); $->getUrl(); $taobao->getUrl(); $google->getUrl(); The complete code is as follows: ## Example url = $par; } function getUrl(){ echo $this->url . PHP_EOL; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title . PHP_EOL; } }$ = new Site; $taobao = new Site; $google = new Site;// Call member functions, set title and URL $->setTitle( "" ); $taobao->setTitle( "Taobao" ); $google->setTitle( "Google Search" );$->setUrl( 'www.' ); $taobao->setUrl( 'www.taobao.com' ); $google->setUrl( 'www.google.com' );// Call member functions, get title and URL $->getTitle(); $taobao->getTitle(); $google->getTitle();$->getUrl(); $taobao->getUrl(); $google->getUrl(); ?> [Run Example Β»](#) Executing the above code, the output is: TaobaoGoogle Search www. www.taobao.com www.google.com * * * ## PHP Constructor A constructor is a special method. It is primarily used to initialize an object when it is created, that is, to assign initial values to the object's member variables, and is used with the `new` operator in statements that create objects. PHP 5 allows developers to define a method within a class as a constructor, with the following syntax: void __construct ([ mixed $args [, $... ]] ) In the example above, we can initialize the `$url` and `$title` variables through the constructor: function __construct( $par1, $par2 ) { $this->url = $par1; $this->title = $par2;} Now we no longer need to call the `setTitle` and `setUrl` methods: ## Example $ = new Site('www.', ''); $taobao = new Site('www.taobao.com', 'Taobao'); $google = new Site('www.google.com', 'Google Search'); // Call member functions, get title and URL $->getTitle(); $taobao->getTitle(); $google->getTitle(); $->getUrl(); $taobao->getUrl(); $google->getUrl(); [Run Example Β»](#) * * * ## Destructor The destructor is opposite to the constructor. When an object ends its lifecycle (for example, the function where the object is located has finished executing), the system automatically executes the destructor. PHP 5 introduced the concept of destructors, which is similar to other object-oriented languages. The syntax is as follows: void __destruct ( void ) ### Example name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "n"; }} $obj = new MyDestructableClass();?> Executing the above code, the output is: ConstructorDestroying MyDestructableClass * * * ## Inheritance PHP uses the keyword **extends** to inherit a class. PHP does not support multiple inheritance. The format is: class Child extends Parent { // code part} ### Example In the example, the `Child_Site` class inherits from the `Site` class and extends its functionality: category = $par;} function getCate(){echo $this->category . PHP_EOL;}} * * * ## Method Overriding If a method inherited from a parent class does not meet the needs of a child class, it can be rewritten. This process is called method overriding, also known as method redefinition. In the example, the `getUrl` and `getTitle` methods are overridden: function getUrl() { echo $this->url . PHP_EOL; return $this->url;} function getTitle(){ echo $this->title . PHP_EOL; return $this->title;} * * * ## Access Control PHP implements access control for properties or methods by adding the keywords `public` (public), `protected` (protected), or `private` (private) in front of them. * **public (public):** Public class members can be accessed from anywhere. * **protected (protected):** Protected class members can be accessed by the class itself, its subclasses, and its parent class. * **private (private):** Private class members can only be accessed by the class in which they are defined. ### Property Access Control Class properties must be defined as public, protected, or private. If defined with `var`, it is treated as public. public; echo $this->protected; echo $this->private; }} $obj = new MyClass(); echo $obj->public; // This line executes normally echo $obj->protected; // This line produces a fatal error echo $obj->private; // This line also produces a fatal error $obj->printHello(); // Outputs Public, Protected, and Private/** * Define MyClass2 */class MyClass2 extends MyClass{ // Can redefine public and protected, but not private protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; }} $obj2 = new MyClass2(); echo $obj2->public; // This line executes normally echo $obj2->private; // Undefined private echo $obj2->protected; // This line produces a fatal error $obj2->printHello(); // Outputs Public, Protected2, and Undefined?> ### Method Access Control Methods in a class can be defined as public, private, or protected. If these keywords are not set, the method defaults to public. MyPublic(); $this->MyProtected(); $this->MyPrivate(); }} $myclass = new MyClass; $myclass->MyPublic(); // This line executes normally $myclass->MyProtected(); // This line produces a fatal error $myclass->MyPrivate(); // This line produces a fatal error $myclass->Foo(); // Public, protected, and private can all be executed/** * Define MyClass2 */class MyClass2 extends MyClass{ // This method is public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // This line produces a fatal error }} $myclass2 = new MyClass2; $myclass2->MyPublic(); // This line executes normally $myclass2->Foo2(); // Public and protected can be executed, but private cannotclass Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublicn"; } private function testPrivate() { echo "Bar::testPrivaten"; }}class Foo extends Bar { public function testPublic() { echo "Foo::testPublicn"; } private function testPrivate() { echo "Foo::testPrivaten"; }} $myFoo = new foo(); $myFoo->test(); // Bar::testPrivate // Foo::testPublic?> * * * ## Interface Using an interface (interface), you can specify which methods a class must implement, but you do not need to define the specific content of these methods. Interfaces are defined using the **interface** keyword, just like defining a standard class, but all methods defined within it are empty. All methods defined in an interface must be public; this is a characteristic of interfaces. To implement an interface, use the **implements** operator. The class must implement all methods defined in the interface; otherwise, a fatal error will occur. A class can implement multiple interfaces, with multiple interface names separated by commas. vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; }} * * * ## Constants You can define values that remain constant within a class as constants. When defining and using constants, you do not need to use the `$` symbol. The value of a constant must be a fixed value; it cannot be a variable, a class property, the result of a mathematical operation, or a function call. Since PHP 5.3.0, you can use a variable to dynamically call a class. However, the value of that variable cannot be a keyword (such as `self`, `parent`, or `static`). ### Example showConstant(); echo $class::constant . PHP_EOL; // Since PHP 5.3.0?> * * * ## Abstract Class Any class, if it has at least one method declared as abstract, must be declared as abstract. A class defined as abstract cannot be instantiated. An abstract method only declares its calling convention (parameters); it cannot define its specific functional implementation. When inheriting an abstract class, the child class must define all abstract methods in the parent class; additionally, the access control of these methods must be the same as (or more permissive than) that in the parent class. For example, if an abstract method is declared as protected, the method implemented in the child class should be declared as protected or public, and cannot be defined as private. getValue() . PHP_EOL; }}class ConcreteClass1 extends AbstractClass{ protected function getValue() { return "ConcreteClass1"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; }}class ConcreteClass2 extends AbstractClass{ public function getValue() { return "ConcreteClass2"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass2"; }} $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') . PHP_EOL; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue('FOO_') . PHP_EOL;?> Executing the above code, the output is: ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2 Furthermore, child class methods can include optional parameters not present in the parent class's abstract method. For example, if a child class defines an optional parameter that is not in the declaration of the parent class's abstract method, it can still run normally. prefixName("Pacman"), "n"; echo $class->prefixName("Pacwoman"), "n";?> The output is: Mr. PacmanMrs. Pacwoman * * * ## Static Keyword Declaring a class property or method as `static` allows it to be accessed without instantiating the class. Static properties cannot be accessed through an instantiated object of a class (but static methods can). Since static methods can be called without an object, the pseudo-variable `$this` is not available in static methods. Static properties cannot be accessed by an object using the `->` operator. Since PHP 5.3.0, you can use a variable to dynamically call a class. However, the value of that variable cannot be the keywords `self`, `parent`, or `static`. staticValue() . PHP_EOL;?> Executing the above program, the output is: foo foo * * * ## Final Keyword PHP 5 introduced a new `final` keyword. If a method in a parent class is declared as `final`, a child class cannot override that method. If a class is declared as `final`, it cannot be inherited. The following code will produce an error when executed: <?php class BaseClass { public function test() { echo "BaseClass::test() called" . PHP_EOL; } final public function moreTesting() { echo "BaseClass::moreTesting() called" . PHP_EOL; }}class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called" . PHP_EOL; }}// Error message Fatal error: Cannot override final met
← Vu3 ComputedVue3 V For β†’