为什么在基本函数上使用 PHP OOP?什么时候使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/716412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use PHP OOP over basic functions and when?
提问by Codex73
There are some posts about this matter, but I didn't clearly get when to use object-oriented coding and when to use programmatic functions in an include. Somebody also mentioned to me that OOP is very heavy to run, and makes more workload. Is this right?
有一些关于这个问题的帖子,但我没有清楚地知道什么时候使用面向对象的编码以及什么时候在包含中使用编程函数。也有人跟我提过,OOP 运行起来很繁重,工作量也比较大。这是正确的吗?
Let's say I have a big file with 50 functions. Why will I want to call these in a class? And not by function_name()? Should I switch and create an object which holds all of my functions? What will be the advantage or specific difference? What benefits does it bring to code OOP in PHP? Modularity?
假设我有一个包含 50 个函数的大文件。为什么我要在课堂上调用这些?而不是通过function_name()?我应该切换并创建一个包含我所有功能的对象吗?优势或具体区别是什么?在 PHP 中编写 OOP 代码有什么好处?模块化?
采纳答案by Majd Taby
In a lot of scenarios, procedural programming is just fine. Using OO for the sake of using it is useless, especially if you're just going to end up with PODobjects (plain-old-data).
在很多场景中,过程式编程就可以了。为了使用它而使用 OO 是没有用的,尤其是如果您只是要以POD对象(plain-old-data)结束时。
The power of OO comes mainly from inheritance and polymorphism. If you use classes, but never use either of those two concepts, you probably don't need to be using a class in the first place.
OO 的威力主要来自于继承和多态。如果您使用类,但从不使用这两个概念中的任何一个,那么您可能一开始就不需要使用类。
One of the nicest places IMO that OO shines in, is allowing you to get rid of switch-on-type code. Consider:
面向对象的 IMO 最棒的地方之一是允许您摆脱开关类型代码。考虑:
function drive($the_car){
switch($the_car){
case 'ferrari':
$all_cars->run_ferrari_code();
break;
case 'mazerati':
$all_cars->run_mazerati_code();
break;
case 'bentley':
$all_cars->run_bentley_code();
break;
}
}
with its OO alternative:
使用它的 OO 替代方案:
function drive($the_car){
$the_car->drive();
}
Polymorphism will allow the proper type of "driving" to happen, based on runtime information.
多态性将允许基于运行时信息的正确类型的“驱动”发生。
Notes on polymorphism:
多态的注意事项:
The second example here has some premisses: That is that all car classes will either extend an abstractclass or implement an interface.
这里的第二个例子有一些前提:那就是所有的汽车类要么扩展一个抽象类,要么实现一个接口。
Both allow you to force extending or implementing classes to define a specific function, such as drive(). This is very powerful as it allows you to drive()all cars without having to know which one you're driving; that is because they're extending an abstract class containing the drive()method or implementing an interface forcing the drive()method to be defined.
两者都允许您强制扩展或实现类来定义特定的函数,例如drive(). 这非常强大,因为它让您drive()无需知道您正在驾驶的是哪一辆汽车;那是因为他们正在扩展一个包含该drive()方法的抽象类或实现一个强制drive()定义该方法的接口。
So as long as you make sure that all your specific cars either extend the abstract class caror implement an interface such as canBeDriven(both of which must declarethe drive()method) you can just call the drive()method on an object which you know is a car (but not what type of car) without fear of it not being defined, as PHP will throw fatal errors at you until you define those methods in your specific car classes.
所以只要你确保所有特定的汽车要么扩展抽象类car或实现一个接口,如canBeDriven(两者都必须申报的drive()方法),你只需拨打drive()你知道一个对象上的方法是一辆汽车(但不什么类型的汽车)而不必担心它没有被定义,因为 PHP 会向您抛出致命错误,直到您在特定的汽车类中定义这些方法。
回答by jerebear
I'll try to keep my answer as an addition because the answers by Majd Taby and Coobird are really good.
我会尽量保留我的答案作为补充,因为 Majd Taby 和 Coobird 的答案非常好。
I was mostly a procedural programmer for several years and didn't fight against OOP programming, but never really saw much relevance...that is until I started working on a team and building more important and complex projects.
几年来,我主要是一名程序程序员,并没有与 OOP 编程作斗争,但从未真正看到过太多相关性……直到我开始在一个团队中工作并构建更重要和更复杂的项目。
OOP really shines, in my opinion, when you need to write lean, easily maintainable code for more complex applications. And mind you, not in every situation, but there are some where procedural just won't work that well.
在我看来,当您需要为更复杂的应用程序编写精简、易于维护的代码时,OOP 真的很出色。请注意,并非在所有情况下都适用,但在某些情况下,程序不会很好地工作。
Most of my examples of great OOP implementations are for projects where I had several things that were all related but all slightly different. Sites with lots of forms, lots of users, lots of products etc.
我的大多数伟大的 OOP 实现示例都是针对我有几件事情都相关但都略有不同的项目。具有多种形式、大量用户、大量产品等的站点。
They all have similar behaviour names like print(), update(), etc...but by encapsulating them as objects and varying the methods' implementations in the classes I can make my code at runtime very simple and clean throughout the site. Also, and this one was key, despite having different behaviours, I could work with different objects using the same method calls throughout the entire application. It allows a second developer to work on actual implementation while I work on deeper code.
它们都有类似的行为名称,如 print()、update() 等……但是通过将它们封装为对象并改变类中方法的实现,我可以使我的代码在运行时在整个站点中变得非常简单和干净。此外,这一点很关键,尽管有不同的行为,但我可以在整个应用程序中使用相同的方法调用来处理不同的对象。它允许第二个开发人员在我处理更深层次的代码时处理实际实现。
I don't know if that helps any but speaking as someone who was in your situation not too long ago, I love OOP.
我不知道这是否有帮助,但作为不久前处于您境况的人来说,我喜欢 OOP。
回答by coobird
Using an object-oriented programming approach rather than a procedural programming approach in a program doesn't really depend on the language (be it PHP or not), but on the type of problem you are trying to solve.
在程序中使用面向对象的编程方法而不是过程式编程方法并不真正取决于语言(无论是不是 PHP),而是取决于您要解决的问题类型。
(I'm just going to use pseudocode in my examples as I am not too familiar with PHP.)
(我将在示例中使用伪代码,因为我对 PHP 不太熟悉。)
For example, if you have a program where you are just performing a bunch of functions in order, then procedural is going to be fine. For example, if it's a simple string manipulation program, a procedural approach would suffice:
例如,如果你有一个程序,你只是按顺序执行一堆功能,那么程序就可以了。例如,如果它是一个简单的字符串操作程序,程序方法就足够了:
perform_truncation(my_string, 10)
to_upper(my_string)
perform_magic(my_string, hat, rabbit)
However, if you're going to deal with many different items (such as files, or any other representation of, well, objects) then an object-oriented approach would be better.
但是,如果您要处理许多不同的项目(例如文件或任何其他对象的表示),那么面向对象的方法会更好。
For example, if you had a bunch of Cars and wanted them to drive, then in procedural, you may do something along the line of:
例如,如果您有一堆Cars 并希望它们 s drive,那么在程序中,您可以按照以下方式做一些事情:
drive_car(first_car)
drive_car(second_car)
Where as, in OOP, the Carcan drive itself:
在 OOP 中,Car可以驱动自己:
RedCar myRedCar();
BlueCar myBlueCar();
myRedCar.drive();
myBlueCar.drive();
And, as each car is a different class, their behavior can be defined differently. Furthermore, they may be both subclasses or Carthey may have common functionality.
而且,由于每辆车属于不同的类别,因此它们的行为可以有不同的定义。此外,它们可能都是子类,Car也可能具有共同的功能。
It really comes down to the type of problem which makes either procedural approach better than object-orientated and vice versa.
这实际上归结为使过程方法优于面向对象的问题类型,反之亦然。
Aside from the issue of procedural or object-oriented, it may be a kind of "code smell" to have one source file with many functions. This can also be said about classes which contain many functionalities which may be better performed as separate functions in separate classes.
抛开面向过程或面向对象的问题,一个源文件有很多功能可能是一种“代码味道”。这也适用于包含许多功能的类,这些功能可以更好地作为单独类中的单独函数执行。
The issue here may be of code organization rather than deciding to pick procedural or object-oriented programming. Organizing functions into separate source files may be what's needed here than to abandon the procedural approach to writing the program.
这里的问题可能是代码组织,而不是决定选择过程式或面向对象的编程。将函数组织到单独的源文件中可能是这里需要的,而不是放弃编写程序的过程方法。
After all, there are plenty of programs written in the procedural programming approach which is well-written and easy to maintain.
毕竟,有很多程序是用过程式编程方法编写的,它们编写得很好且易于维护。
回答by Volksman
Lets say I have a big file with 50 functions, why will I want to call these in a class? and not by function_name(). Should I switch and create object which holds all of my functions?
假设我有一个包含 50 个函数的大文件,为什么我要在类中调用这些函数?而不是通过 function_name()。我应该切换并创建包含我所有功能的对象吗?
Moving to OOP should not been seen as a simple 'switch' in the way you describe above.
转移到 OOP 不应被视为上述方式的简单“切换”。
OOP requires a completely different way of thinking about programming which involves rewiring your brain. As rewiring a brain doesn't happen overnight many people are unwilling to expose themselves to the required rewiring process. Unfortunately the rewiring is going to take an investment in time and effort: research, tutorials, trial and error.
OOP 需要一种完全不同的编程思维方式,这涉及重新连接您的大脑。由于重新连接大脑不会在一夜之间发生,因此许多人不愿意将自己暴露在所需的重新布线过程中。不幸的是,重新布线需要投入时间和精力:研究、教程、反复试验。
It really involves taking a step back and learning about the concepts behind OOP but the payback will be well worth it speaking as someone who went through this process in the pre www days.
它确实涉及退后一步并了解 OOP 背后的概念,但作为在 www 前的日子里经历过这个过程的人来说,回报将是非常值得的。
After you 'get it' and follow OOP best practices in your everyday you'll be telling others how your programming life has changed for the better.
在您“了解”并在日常生活中遵循 OOP 最佳实践后,您将告诉其他人您的编程生活如何变得更好。
Once you really understand OOP you will have answered your own question.
一旦你真正理解了 OOP,你就会回答你自己的问题。
回答by Dan
OOP allows you to create structured containers of code, called classes, which can be parents/children of one another. This can help with building an application as it is easier to maintain and can, if done properly reduce code redundancy. OOP does add a bit overhead but it isn't really noticeable and is outweighed by the unmaintainablity of procedural code. If your writing a big app, def go OO, especially if it is going to be worked on by many people.
OOP 允许您创建结构化的代码容器,称为类,它们可以是彼此的父/子。这有助于构建应用程序,因为它更易于维护,并且如果正确完成,可以减少代码冗余。OOP 确实增加了一点开销,但它并不是很明显,并且被过程代码的不可维护性所抵消。如果您正在编写一个大型应用程序,那么一定要面向对象,尤其是当它要由很多人使用时。
For example, say you are designing a simple website. You could create a Page object. The page object is responsible for going to the database and getting various settings for the page, such as meta data, title tags, or even the number of certain "components" on the page and their type (such as a calendar control, a widget, etc).
例如,假设您正在设计一个简单的网站。您可以创建一个 Page 对象。页面对象负责进入数据库并获取页面的各种设置,例如元数据、标题标签,甚至页面上某些“组件”的数量及其类型(例如日历控件、小部件, 等等)。
Then, you can create another class, say Index, that extends Page. Index would be the index or home page. If you had a catalog of products, you could have Catalog class extend page. Since both your catalog section and your homepage need to get data from the database concerning the metadata of the page and the basic construction of the page, having 1 object that does it already for you helps. In both of these situations, page does all the work and gets the page data from the database, loads it into variables, which are then accessible in both your index class and your catalog class. You don't have to write code to go into the database and get it again in each page you write.
然后,您可以创建另一个类,比如 Index,它扩展了 Page。索引将是索引或主页。如果您有产品目录,则可以拥有 Catalog 类扩展页面。由于您的目录部分和主页都需要从数据库中获取有关页面元数据和页面基本结构的数据,因此拥有 1 个已经为您执行此操作的对象会有所帮助。在这两种情况下,页面都会完成所有工作并从数据库中获取页面数据,将其加载到变量中,然后在您的索引类和目录类中都可以访问这些数据。您不必编写代码即可进入数据库并在您编写的每个页面中再次获取它。
Now there are other ways to do this procedurally, such as with an includes. However, you will find yourself making less mistakes and errors. For example, you can define an abstract method in your Page class. This means that this method MUST be defined in any object that extends it. So say you created a setPageAttributes() function as abstract in your Page class. When you do this you create an empty function. When you create your index class, you HAVE TO create a setPageAttributes() function (with the intent on filling it in, such as accessing the variables defined in the Page class and using it to set the actual elements on the page, template, or view you are using) or you get a PHP error.
现在还有其他方法可以在程序上执行此操作,例如使用包含。但是,您会发现自己犯的错误和错误更少。例如,您可以在 Page 类中定义一个抽象方法。这意味着必须在扩展它的任何对象中定义此方法。因此,假设您在 Page 类中创建了一个 setPageAttributes() 函数作为抽象函数。当你这样做时,你创建了一个空函数。创建索引类时,必须创建一个 setPageAttributes() 函数(目的是填充它,例如访问 Page 类中定义的变量并使用它来设置页面、模板或查看您正在使用的)或您收到 PHP 错误。
If you are working with other people to get your project written, abstract methods will tell the person, "Hey, you need to define these functions in any code you write". This forced the application to be consistent.
如果您正在与其他人合作编写您的项目,抽象方法将告诉此人,“嘿,您需要在您编写的任何代码中定义这些函数”。这迫使应用程序保持一致。
Finally, you cannot go to frameworks such as MVC formats if you do not do OOP. While it is not necessary to go to MVC and there is some debate, it does separate out all the components of the application and is necessary in environments where many people (designers, coders, marketing employees) work on the same code.
最后,不做OOP就不能上MVC格式之类的框架。虽然没有必要使用 MVC 并且存在一些争论,但它确实将应用程序的所有组件分开,并且在许多人(设计师、编码员、营销人员)处理相同代码的环境中是必要的。
回答by farzad
I can't say which one is better. but in my experience you can have better code management using OOP. you know which code is where, what functionality is defined in which file, etc. about the runtime overhead for OOP I read somewhere (and I think it is true) that if you write a bad code in classic functions, and the same bad code in OOP, the function version works better. so if your code is not written bad, there is no proof that OOP is keeping your application slow. also remember that these "slow" and "overhead" stuff are all measured in milliseconds. so if your application is not serving a lot of users (like more than 100 users in a minute), you might not feel any difference.
我不能说哪个更好。但根据我的经验,您可以使用 OOP 进行更好的代码管理。你知道哪个代码在哪里,在哪个文件中定义了哪些功能,等等。关于 OOP 的运行时开销我在某处读到(我认为这是真的)如果你在经典函数中写了一段糟糕的代码,同样的糟糕代码在 OOP 中,函数版本效果更好。因此,如果您的代码写得不错,则没有证据表明 OOP 使您的应用程序变慢。还请记住,这些“慢”和“开销”的东西都是以毫秒为单位的。因此,如果您的应用程序没有为大量用户提供服务(例如一分钟内超过 100 个用户),您可能不会感觉到任何区别。
回答by Luc M
If you have 50 functions instead of 50 static methods into Utilities class, you "pollute" the global namespace.
如果您在 Utilities 类中有 50 个函数而不是 50 个静态方法,那么您“污染”了全局命名空间。
Using a class with 50 static methods, method names are local to your class.
使用具有 50 个静态方法的类,方法名称对于您的类来说是本地的。
回答by Ankur Kumar Singh
Use of the oop gives you following benefit:
使用 oop 为您带来以下好处:
- Structuring
- Reusability
- Easy Maintenance
- Encapsulation of the Data
- 结构化
- 可重用性
- 易于维护
- 数据的封装
Coming to the point of making big file with 50 function. You can do that but when it comes to the flow of the function and how the data data will be bind between every function will be a biggest problem.
到了用50个功能制作大文件的地步。您可以这样做,但是当涉及到函数的流程以及如何在每个函数之间绑定数据数据时,这将是一个最大的问题。
Also for the future maintenance if you want to replace the biggest chunk of the flow, trust me you have to go to every function and play around it. Also you never know how your functions are used in other part of the code. So Object Oriented programming is always advisable.
同样对于未来的维护,如果您想替换流程的最大部分,请相信我,您必须访问每个功能并围绕它进行操作。此外,您永远不知道您的函数在代码的其他部分是如何使用的。所以面向对象编程总是可取的。
For the detailed about the benifits you can read my post on OOP in PHP
有关好处的详细信息,您可以阅读我在 PHP 中的 OOP 上的帖子
回答by Andy Gee
The accepted answer seems to have neglected to state that it is possible to call functions based on a variable name such as in the example herew:
接受的答案似乎忽略了可以根据变量名称调用函数,例如在此处的示例中:
function drive($the_car){
$the_car();
}
Admittedly there would need to be a function for each car in this instance but it's a lot more efficient than the suggested switch statement.
诚然,在这种情况下,每辆车都需要一个函数,但它比建议的 switch 语句效率高得多。
Additional variables can be supplied easily as such:
可以轻松提供其他变量,如下所示:
function operate($the_car,$action){
$the_car($action);
}
function ferrari($action){
switch($action){
case 'drive':
echo 'Driving';
break;
case 'stop':
echo 'Stopped';
break;
default: return;
}
}
operate('ferrari','drive');
There is a switch statement here but it's to supply additional functionality that was not in the original example so it's in no way a contradiction.
这里有一个 switch 语句,但它提供了原始示例中没有的附加功能,因此这绝不是矛盾的。
回答by Kirandeep Kaur
The OOPs concept is used in PHP, so as to secure the code. As all the queries are written in function file instead of code file so no one can easily hack our code. So it is better to use classes in PHP instead of directly writing the queries.
PHP 中使用了 OOPs 概念,以保护代码。由于所有查询都是在函数文件而不是代码文件中编写的,因此没有人可以轻易破解我们的代码。所以最好在 PHP 中使用类而不是直接编写查询。

