search
HomeBackend DevelopmentPHP TutorialMethods to develop large-scale PHP projects_PHP tutorial
Methods to develop large-scale PHP projects_PHP tutorialJul 21, 2016 pm 04:09 PM
oopphpexistLargeobjectdevelopmethodPurposeprogrammingFor


Methods for developing large-scale PHP projects Object-oriented programming (OOP, Object Oriented Programming) in PHP is introduced here. You'll be shown how to reduce coding and improve quality by using some OOP concepts and PHP techniques. Good luck!

The concept of object-oriented programming:
Different authors may have different opinions, but an OOP language must have the following aspects:

Abstract data types and information encapsulation
Inheritance
Polymorphism

is encapsulated through classes in PHP:

Code:

class Something {
// In OOP classes, usually the first character is uppercase
var $x;
function setX($v) {
// The method starts with a lowercase word and then uses uppercase letters to separate the words, For example getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>



Of course you can define it according to your own preferences, but it is better to maintain a standard, which will be more effective.

Data members are defined in the class using the "var" declaration. Before the data members are assigned a value, they have no type. A data member can be an integer, an array, an associative array, or an object.

Methods are defined as functions in the class. When accessing class member variables in a method, you should use $this->name. Otherwise, for a method, it can only be a local variable.

Use the new operator to create an object:

$obj=new Something;

You can then use member functions via:

$obj- >setX(5);
$see=$obj->getX();

In this example, the setX member function assigns 5 to the member variable x of the object (not the class) , then getX returns its value 5.

You can access data members through class references like: $obj->x=6. This is not a good OOP habit. I strongly recommend accessing member variables through methods. You will be a good OOP programmer if you treat member variables as unmanipulable and use methods only through object handles. Unfortunately, PHP does not support declaring private member variables, so bad code is allowed in PHP.

Inheritance is easy to implement in PHP, just use the extend keyword.

Code:

class Another extends Something {
var $y;
function setY($v) {
$this-> ;y=$v;
}
function getY() {
return $this->y;
}
}
?>



The object of "Another" class now has all the data members and methods of the parent class (Something), and also adds its own data members and methods.

You can use the

code:

$obj2=new Something;
$obj2->setX(6);
$obj2-> setY(7);



PHP currently does not support multiple inheritance, so you cannot derive new classes from two or more classes.

You can redefine a method in a derived class. If we redefine the getX method in the "Another" class, we cannot use the getX method in "Something". If you declare a data member in a derived class with the same name as the base class, it will "hide" the base class data member when you deal with it.

You can define constructors in your class. The constructor is a method with the same name as the class name, which is called when you create an object of the class, for example:

Code:

class Something {
var $x;
function Something($y) {
$this->x=$y;
}
function setX($v) {
$this-> ;x=$v;
}
function getX() {
return $this->x;
}
}
?>



So you can create an object by:

$obj=new Something(6);

The constructor will automatically assign 6 to the data variable x. Constructors and methods are normal PHP functions, so you can use default parameters.

function Something($x="3",$y="5")

Then:

$obj=new Something(); // x=3 and y=5
$obj=new Something(8); // x=8 and y=5
$obj=new Something(8,9); // x=8 and y=9

The default parameters use the C++ method, so you cannot ignore the value of Y and give a default parameter to X. The parameters are assigned from left to right. If the parameters passed in are less than the required parameters, the other The default parameters will be used.

When an object of a derived class is created, only its constructor is called, and the constructor of the parent class is not called. If you want to call the constructor of the base class, you must do it in the derived class. Explicit call in constructor. This can be done because all methods of the parent class are available in the derived class.

Code:

function Another() {
$this->y=5;
$this->Something();
//Explicitly calling the base class constructor
}
?>



A good mechanism for OOP is to use abstract classes. Abstract classes cannot be instantiated and can only provide an interface to derived classes. Designers often use abstract classes to force programmers to derive from a base class, thus ensuring that the new class contains some desired functionality.There is no standard method in PHP, but:

If you need this feature, you can define a base class and add a "die" call after its constructor, so that you can ensure that the base class is Non-instantiable, now adds a "die" statement after each method (interface), so if a programmer does not override the method in a derived class, an error will be raised. And because PHP is untyped, you may need to confirm that an object is a derived class from your base class, then add a method in the base class to define the identity of the class (return some kind of identification id), and in your Check this value when receiving an object parameter. Of course, if an evil programmer overrides this method in a derived class, this method will not work, but generally the problem is found in lazy programmers, not evil programmers.

Of course, it's nice to be able to keep the base classes invisible to programmers, who can just print out the interfaces and do their job.

There is no destructor in PHP.

Overloading (unlike overriding) is not supported in PHP. In OOP, you can overload a method to implement two or more methods with the same name but different numbers or types of parameters (depending on the language). PHP is a loosely typed language, so overloading by type does not work, but overloading by different number of parameters does not work either.

Sometimes it's good to overload constructors in OOP so that you can create objects through different methods (passing different numbers of arguments). The trick to implement it in PHP
is:

Code:

class Myclass {
function Myclass() {
$name= "Myclass".func_num_args();
$this->$name();
//Note that $this->name() is generally wrong, but here $name is the one that will be called Method name
}
function Myclass1($x) {
code;
}
function Myclass2($x,$y) {
code;
}
}
?>



Using this class is transparent to the user through additional processing in the class:

$obj1=new Myclass( '1'); //Myclass1 will be called

$obj2=new Myclass('1','2'); //Myclass2 will be called

Sometimes this is very useful.

Polymorphism
Polymorphism is an ability of an object, which can decide which object method to call based on the passed object parameters at runtime. For example, if you have a figure class, it defines a draw method. And derived the circle and rectangle classes, in the derived class you override the draw method, you may also have a function that expects a parameter x, and can call $x->draw(). If you have polymorphism, which draw method is called depends on the type of object you pass to the function.

Polymorphism in interpreted languages ​​like PHP (imagine a C++ compiler generating code like this, which method should you call? You also don’t know what type of object you have, well, That's not the point) is very easy and natural. So of course PHP supports polymorphism.

Code:

function niceDrawing($x) {
//Assume this is a method of the Board class
$x->draw ();
}
$obj=new Circle(3,187);
$obj2=new Rectangle(4,5);
$board->niceDrawing($obj);
//The draw method of Circle will be called
$board->niceDrawing($obj2);
//The draw method of Rectangle will be called
?>



Object-oriented programming with PHP
Some "purists" may say that PHP is not a true object-oriented language, and this is true. PHP is a hybrid language, you can use OOP or traditional procedural programming. However, for larger projects, you may want/need to use pure OOP in PHP to declare classes, and only use objects and classes in your project.

As projects get larger, it may be helpful to use OOP. OOP code is easy to maintain, easy to understand and reuse. These are the foundations of software engineering
. Applying these concepts in web-based projects becomes the key to future website success.

Advanced OOP technologies in PHP
After looking at the basic OOP concepts, I can show you more advanced technologies:

Serializing (Serializing)
PHP does not Support for persistent objects. In OOP, a persistent object is an object that can maintain state and functionality among references in multiple applications. This means having the ability to save the object to a file or database, and to load the object later. This is the so-called serialization mechanism. PHP has a serialization method that can be called on an object, and the serialization method can return a string representation of the object. However, serialization only saves the member data of the object and not the methods.

In PHP4, if you serialize the object into the string $s, then release the object, and then deserialize the object into $obj, you can continue to use the object's methods! I don't recommend doing this because (a) there is no guarantee in the documentation that this behavior will still work in future versions. (b) This may lead to a misunderstanding when you save a serialized version to disk and exit the script.When you run this script later, you can't expect that when you deserialize an object, the object's methods will be there, because the string representation doesn't include methods at all.

In short, serialization in PHP is very useful for saving member variables of objects. (You can also serialize related arrays and arrays into a file).

Example:

Code:

$obj=new Classfoo();
$str=serialize($obj);
//A few months later
//Load str from disk
$obj2=unserialize($str)
?>



You restore Member data is included, but methods are not included (according to the documentation). This results in the only way to access member variables (you have no other way!) by something like using $obj2->x, so don't try it at home.

There are some ways to solve this problem, I'm leaving them out because they are too bad for this concise article.

Use classes for data storage
One very nice thing about PHP and OOP is that you can easily define a class to operate something and use it whenever you want The corresponding class can be called. Suppose you have an HTML form that allows the user to select a product by selecting the product ID number. There is product information in the database, and you want to display the product, its price, etc. You have different types of products, and the same action can mean different things to different products. For example, displaying a sound might mean playing it, but for other kinds of products it might mean displaying an image stored in a database. You can use OOP or PHP to reduce coding and improve quality:

Define a class for a product, define the methods it should have (eg: display), then define a class for each type of product, from After the product class comes out (SoundItem class, ViewableItem class, etc.), override the methods in the product class to make them act as you want.

Name the class according to the type field of each product in the database. A typical product table may have (id, type, price, description, etc. fields)... and then process the script , you can retrieve the type value from the database and instantiate an object named type:


Code:

$obj=new $ type();
$obj->action();
?>



This is a very good feature of PHP, you don’t need to consider objects Type, call the display method or other methods of $obj. Using this technique, you don't need to modify the script to add a new type of object, just a class to handle it.

This function is very powerful. Just define methods without considering the types of all objects, implement them in different classes in different methods, and then use them on any object in the main script, without if. ..else, there is no need for two programmers, only happiness.

Now you agree that programming is easy, maintenance is cheap, and reusability is true?

If you manage a group of programmers, assigning work is simple, each person may be responsible for a type of object and the class that handles it.

Internationalization can be achieved through this technology, just apply the corresponding class according to the language field selected by the user, and so on.


Copy and Clone
When you create an object of $obj, you can copy the object by $obj2=$obj. The new object is a copy of $obj (not a reference ), so it has the state of $obj at that time. Sometimes, you don't want to do this. You just want to generate a new object like the obj class. You can call the constructor of the class by using the new statement. This can also be achieved in PHP through serialization and a base class, but all other classes must be derived from the base class.


Entering the danger zone
When you serialize an object, you will get a string in some format. If you are interested, you can investigate it. Among them, there are classes in the string name (so great!), you can take it out, like:

Code:

$herring=serialize($obj);
$vec=explode(':',$herring);
$nam=str_replace(""",'',$vec[2]);
?>



So assuming you create a "Universe" class and force all classes to extend from universe, you can define a clone method in universe, as follows:

Code:

class Universe {
function clone() {
$herring=serialize($this);
$vec=explode(':',$herring);
$nam=str_replace(""",'',$vec[2]);
$ret=new $nam;
return $ret;
}
}
//Then
$obj=new Something();
//Expand from Universe
$other=$obj->clone();
?>



What you get is a new object of the Something class, which is the same as the object created by using the new method and calling the constructor. I don't know if this will work for you, but it's a good rule of thumb that the universe class knows the name of the derived class. Imagination is the only limit. (Source: Feng Shan)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314509.htmlTechArticleHow to develop large-scale PHP projects Here is an introduction to object-oriented programming (OOP, Object Oriented Programming) in PHP. Will show you how to use some OOP concepts and PHP techniques to...
Statement
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
Nuitka简介:编译和分发Python的更好方法Nuitka简介:编译和分发Python的更好方法Apr 13, 2023 pm 12:55 PM

译者 | 李睿审校 | 孙淑娟随着Python越来越受欢迎,其局限性也越来越明显。一方面,编写Python应用程序并将其分发给没有安装Python的人员可能非常困难。解决这一问题的最常见方法是将程序与其所有支持库和文件以及Python运行时打包在一起。有一些工具可以做到这一点,例如PyInstaller,但它们需要大量的缓存才能正常工作。更重要的是,通常可以从生成的包中提取Python程序的源代码。在某些情况下,这会破坏交易。第三方项目Nuitka提供了一个激进的解决方案。它将Python程序编

我创建了一个由 ChatGPT API 提供支持的语音聊天机器人,方法请收下我创建了一个由 ChatGPT API 提供支持的语音聊天机器人,方法请收下Apr 07, 2023 pm 11:01 PM

今天这篇文章的重点是使用 ChatGPT API 创建私人语音 Chatbot Web 应用程序。目的是探索和发现人工智能的更多潜在用例和商业机会。我将逐步指导您完成开发过程,以确保您理解并可以复制自己的过程。为什么需要不是每个人都欢迎基于打字的服务,想象一下仍在学习写作技巧的孩子或无法在屏幕上正确看到单词的老年人。基于语音的 AI Chatbot 是解决这个问题的方法,就像它如何帮助我的孩子要求他的语音 Chatbot 给他读睡前故事一样。鉴于现有可用的助手选项,例如,苹果的 Siri 和亚马

ChatGPT 的五大功能可以帮助你提高代码质量ChatGPT 的五大功能可以帮助你提高代码质量Apr 14, 2023 pm 02:58 PM

ChatGPT 目前彻底改变了开发代码的方式,然而,大多数软件开发人员和数据专家仍然没有使用 ChatGPT 来改进和简化他们的工作。这就是为什么我在这里概述 5 个不同的功能,以提高我们的日常工作速度和质量。我们可以在日常工作中使用它们。现在,我们一起来了解一下吧。注意:切勿在 ChatGPT 中使用关键代码或信息。01.生成项目代码的框架从头开始构建新项目时,ChatGPT 是我的秘密武器。只需几个提示,它就可以生成我需要的代码框架,包括我选择的技术、框架和版本。它不仅为我节省了至少一个小时

解决Batch Norm层等短板的开放环境解决方案解决Batch Norm层等短板的开放环境解决方案Apr 26, 2023 am 10:01 AM

测试时自适应(Test-TimeAdaptation,TTA)方法在测试阶段指导模型进行快速无监督/自监督学习,是当前用于提升深度模型分布外泛化能力的一种强有效工具。然而在动态开放场景中,稳定性不足仍是现有TTA方法的一大短板,严重阻碍了其实际部署。为此,来自华南理工大学、腾讯AILab及新加坡国立大学的研究团队,从统一的角度对现有TTA方法在动态场景下不稳定原因进行分析,指出依赖于Batch的归一化层是导致不稳定的关键原因之一,另外测试数据流中某些具有噪声/大规模梯度的样本

摔倒检测-完全用ChatGPT开发,分享如何正确地向ChatGPT提问摔倒检测-完全用ChatGPT开发,分享如何正确地向ChatGPT提问Apr 07, 2023 pm 03:06 PM

哈喽,大家好。之前给大家分享过摔倒识别、打架识别​,今天以摔倒识别​为例,我们看看能不能完全交给ChatGPT来做。让ChatGPT​来做这件事,最核心的是如何向ChatGPT​提问,把问题一股脑的直接丢给ChatGPT​,如:用 Python 写个摔倒检测代码 是不可取的, 而是要像挤牙膏一样,一点一点引导ChatGPT​得到准确的答案,从而才能真正让ChatGPT提高我们解决问题的效率。今天分享的摔倒识别​案例,与ChatGPT​对话的思路清晰,代码可用度高,按照GPT​返回的结果完全可以开

17 个可以实现高效工作与在线赚钱的 AI 工具网站17 个可以实现高效工作与在线赚钱的 AI 工具网站Apr 11, 2023 pm 04:13 PM

自 2020 年以来,内容开发领域已经感受到人工智能工具的存在。1.Jasper AI网址:https://www.jasper.ai在可用的 AI 文案写作工具中,Jasper 作为那些寻求通过内容生成赚钱的人来讲,它是经济实惠且高效的选择之一。该工具精通短格式和长格式内容均能完成。Jasper 拥有一系列功能,包括无需切换到模板即可快速生成内容的命令、用于创建文章的高效长格式编辑器,以及包含有助于创建各种类型内容的向导的内容工作流,例如,博客文章、销售文案和重写。Jasper Chat 是该

为什么特斯拉的人形机器人长得并不像人?一文了解恐怖谷效应对机器人公司的影响为什么特斯拉的人形机器人长得并不像人?一文了解恐怖谷效应对机器人公司的影响Apr 14, 2023 pm 11:13 PM

1970年,机器人专家森政弘(MasahiroMori)首次描述了「恐怖谷」的影响,这一概念对机器人领域产生了巨大影响。「恐怖谷」效应描述了当人类看到类似人类的物体,特别是机器人时所表现出的积极和消极反应。恐怖谷效应理论认为,机器人的外观和动作越像人,我们对它的同理心就越强。然而,在某些时候,机器人或虚拟人物变得过于逼真,但又不那么像人时,我们大脑的视觉处理系统就会被混淆。最终,我们会深深地陷入一种对机器人非常消极的情绪状态里。森政弘的假设指出:由于机器人与人类在外表、动作上相似,所以人类亦会对

如何使用Azure Bot Services创建聊天机器人的分步说明如何使用Azure Bot Services创建聊天机器人的分步说明Apr 11, 2023 pm 06:34 PM

译者 | 李睿​审校 | 孙淑娟​信使、网络服务和其他软件都离不开机器人(bot)。而在软件开发和应用中,机器人是一种应用程序,旨在自动执行(或根据预设脚本执行)响应用户请求创建的操作。在本文中, NIX United公司的.NET​开发人员Daniil Mikhov介绍了使用微软Azure Bot Services创建聊天机器人的一个例子。本文将对想要使用该服务开发聊天机器人的开发人员有所帮助。 为什么使用Azure Bot Services? ​在Azure Bot Services上开发聊

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)