Table of Contents
PHP Object-Oriented Programming Learning Part 2
Home Backend Development PHP Tutorial PHP object-oriented programming learning part 2_PHP tutorial

PHP object-oriented programming learning part 2_PHP tutorial

Jul 13, 2016 am 10:08 AM
object

PHP Object-Oriented Programming Learning Part 2

Interface

Interface defines the common behaviors of different classes, and then implements different functions in different classes. When many people develop a project together, they may all call some classes written by others. Then you may ask, how do I know how to name the implementation method of a certain function? At this time, the PHP interface class interface is It works. When we define an interface class, the methods in it must be implemented by the following subclasses, such as:

<?php
interface Shop  
{  
	public function buy($gid);  
	public function sell($gid);  
	public function view($gid);  
}  

class BaseShop implements Shop  
{  
	public function buy($gid)  
	{  
		echo(&#39;你购买了ID为 :&#39;.$gid.&#39;的商品&#39;);  
	}  
	public function sell($gid)  
	{  
		echo(&#39;你卖了ID为 :&#39;.$gid.&#39;的商品&#39;);  
	}  
	public function view($gid)  
	{  
		echo(&#39;你查看了ID为 :&#39;.$gid.&#39;的商品&#39;);  
	}  
}  
?>
Copy after login
Polymorphism
Because there can be many implementation methods of interfaces, there are many specific implementations of the top methods in the interface. This feature is called polymorphism. Polymorphism refers to the ability in object-oriented to redefine or change the nature and behavior of a class according to the context in which the class is used.
PHP does not support overloading to achieve polymorphism, but PHP can achieve polymorphic effects in different directions.
Case 1:

<?
interface User{ // User接口
	public function  getName();
	public function setName($_name);
}

class NormalUser implements User { // 实现接口的类.
	private $name;
	public function getName(){
		return $this->name;
	}
	public function setName($_name){
		$this->name = $_name;
	}
}

class UserAdmin{ //操作.
	public static function  ChangeUserName(User $_user,$_userName){
		$_user->setName($_userName);
	}
}

$normalUser = new NormalUser();
UserAdmin::ChangeUserName($normalUser,"Tom");//这里传入的是 NormalUser的实例.
echo $normalUser->getName();
?>
Copy after login
Case 2:

<?php
// 通过可变参数来达到改变参数数量重载的目的
// 不是必须传入的参数,必须在函数定义时赋初始值
function open_database($DB, $cache_size_or_values=null, $cache_size=null)
{
    switch (function_num_args())  // 通过function_num_args()函数计算传入参数的个数,根据个数来判断接下来的操作
    {
        case 1:
            $r = select_db($DB);
            break;
        case 2:
            $r = select_db($DB, $cache_size_or_values);
            break;
        case 3:
            $r = select_db($DB, $cache_size_or_values, $cache_size);
            break;
    }
    return is_resource($r);
}
?>
Copy after login
Abstract class
Abstract classes are between interfaces and class definitions
PHP5 supports abstract classes and abstract methods. Abstract classes cannot be instantiated directly; you must first inherit from the abstract class and then instantiate the subclass. An abstract class must contain at least one abstract method. If a class method is declared abstract, it cannot contain concrete functional implementations.
When inheriting an abstract class, the subclass must implement all abstract methods in the abstract class; in addition, the visibility of these methods must be the same as in the abstract class (or more relaxed). If an abstract method in an abstract class is declared protected, then the method implemented in the subclass should be declared protected or public, and cannot be defined as private.
<?php
abstract class AbstractClass
{
 // 强制要求子类定义这些方法
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // 普通方法(非抽象方法)
    public function printOut() {
        print $this->getValue() . " ";
    }
}

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(&#39;FOO_&#39;) ." ";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue(&#39;FOO_&#39;) ." ";
?>
Copy after login




www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/953323.htmlTechArticlePHP Object-Oriented Programming Learning Part 2 Interface The interface is to define the common behaviors of different classes, and then use them in different Different functions are implemented in the classes. When many people develop a project together...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Convert an array or object to a JSON string using PHP's json_encode() function Convert an array or object to a JSON string using PHP's json_encode() function Nov 03, 2023 pm 03:30 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples. Syntax The syntax of the json_encode() function is as follows: st

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

Use Python's __contains__() function to define the containment operation of an object Use Python's __contains__() function to define the containment operation of an object Aug 22, 2023 pm 04:23 PM

Use Python's __contains__() function to define the containment operation of an object. Python is a concise and powerful programming language that provides many powerful features to handle various types of data. One of them is to implement the containment operation of objects by defining the __contains__() function. This article will introduce how to use the __contains__() function to define the containment operation of an object, and give some sample code. The __contains__() function is Pytho

Source code exploration: How are objects called in Python? Source code exploration: How are objects called in Python? May 11, 2023 am 11:46 AM

Wedge We know that objects are created in two main ways, one is through Python/CAPI, and the other is by calling a type object. For instance objects of built-in types, both methods are supported. For example, lists can be created through [] or list(). The former is Python/CAPI and the latter is a calling type object. But for instance objects of custom classes, we can only create them by calling type objects. If an object can be called, then the object is callable, otherwise it is not callable. Determining whether an object is callable depends on whether a method is defined in its corresponding type object. like

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

Detailed explanation of 5 loop traversal methods of Javascript objects Detailed explanation of 5 loop traversal methods of Javascript objects Aug 04, 2022 pm 05:28 PM

How to loop through Javascript objects? The following article will introduce five JS object traversal methods in detail, and briefly compare these five methods. I hope it will be helpful to you!

Use Python's __le__() function to define a less than or equal comparison of two objects Use Python's __le__() function to define a less than or equal comparison of two objects Aug 21, 2023 pm 09:29 PM

Title: Using Python's __le__() function to define a less than or equal comparison of two objects In Python, we can define comparison operations between objects by using special methods. One of them is the __le__() function, which is used to define less than or equal comparisons. The __le__() function is a magic method in Python and is a special function used to implement the "less than or equal" operation. When we compare two objects using the less than or equal operator (&lt;=), Python

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

See all articles