php面向对象编程
Imagine if someone tells you to hammer 10 nails into a board. The best tool for the job would be a hammer, right? You COULD go take lessons on how to use a Super Screwdriver 9000, but that would make absolutely no sense. A Super Screwdriver 9000 might be able to use any type of screw in the world, but it wouldn't help you hammer in those 10 nails, so you wouldn't use it and after a while, you would start to forget what you've learned about that special screwdriver.
想象一下,如果有人告诉您将10钉子钉在板上。 最好的工具是锤子,对不对? 您可能会上过如何使用Super Screwdriver 9000的课程,但这绝对没有任何意义。 超级螺丝刀9000可能可以使用世界上任何类型的螺丝,但并不能帮助您锤击这10个钉子,因此您将不使用它,过一会儿,您将开始忘记自己所用的螺丝钉。我已经了解了那把特殊的螺丝刀。
This is a common problem for experienced PHP developers that are learning the (relatively) new object-oriented programming (OOP) capabilities of PHP, or for anyone that is trying to learn how to do OOP in PHP. They want to learn how to do it, but they don't know WHEN to use it properly, so they don't use it, and then the knowledge just fades away after a while.
对于正在学习(相对)新的面向对象编程(OOP)PHP功能的经验丰富PHP开发人员,或者正在尝试学习如何在PHP中进行OOP的任何人来说,这都是一个常见问题。 他们想学习如何做,但是他们不知道何时适当地使用它,因此他们不使用它,然后一段时间之后,这些知识就会消失。
传统与面向对象 (Traditional vs. Object-Oriented)
因此,让我们开始比较传统的自顶向下编程与面向对象的编程。 假设我们正在尝试定义一些描述两个房屋的变量。Traditional top-programming might look like this:
传统的顶级编程可能看起来像这样:
<?
$house1_type = "Apartment";
$house1_address = "123 Main Street";
$house2_type = "Mansion";
$house2_address = "123 Money Street";
?>
<?
class House
{
public $type = "";
public $address = "";
public $residents = array();
}
$house1 = new House();
$house1->type = "Apartment";
$house1->address = "123 Main Street";
$house2 = new House();
$house2->type = "Mansion";
$house2->address = "123 Money Street";
?>
面向对象编程:为什么以及何时进行 (Object-Oriented Programming: Why and When to Do It)
这是面向对象编程和传统编程之间的基本最佳区别:Object-Oriented Programming is more organized.
面向对象的编程更加有条理。
That's not to say that it's always better, though! I have a REALLY messy home office, but I know exactly where everything is. My wife, on the other hand, hates the mess and it would take her a long time to find anything in it. But if I'm the only one using that office, then I can keep it messy, right?
但这并不是说它总是更好! 我的家庭办公室真的很乱,但是我确切地知道一切在哪里。 另一方面,我的妻子讨厌这个烂摊子,要花很长时间才能在里面找到任何东西。 但是,如果我是唯一使用该办公室的人,那么我可以让它保持混乱,对吗?
The differences in programming are similar. Traditional top-down programming can START OUT clean, and if your script will always stay small, then it's a great way to bang out a quick, efficient program. If your application grows, then it will almost always get messy over time as you add more features and stuff. The larger the application becomes, the harder it becomes to maintain and document. Plus, as an application grows, you often end up having more people work on it with you. Be honest - would YOU want to suddenly have to work on a large project with tons of messy code everywhere? Probably not.
编程上的差异相似。 传统的自上而下的编程可以从头开始,如果您的脚本始终很小,那么这是发布快速,高效程序的好方法。 如果您的应用程序不断增长,那么随着您添加更多功能和内容,随着时间的流逝,它几乎总是变得混乱。 应用程序越大,维护和记录文件就越困难。 另外,随着应用程序的增长,您通常最终会吸引更多的人与您一起工作。 老实说-您是否想突然不得不在一个到处都有大量
Back to my messy office - I could spend a few minutes to organize all my papers and junk and put them into labeled boxes. If my wife kept having to go into the office to get documents, or if I hired someone to work in the room with me, then it would benefit all of us for me to be organized. Nobody would have to ask me where to find things, and I'd probably still be able to find things pretty easily. Plus, as I hired more and more people, I would get more and more benefit out of keeping the office organized. I could even have people dedicated to working on documents in specific boxes. Or, if I wanted to send all of my tax documents to my friend who does my taxes, then I could just send him/her the box labeled "Tax Stuff" instead of trying to go around and gather up all the different papers from the mess. (I'm using these examples for a reason - you'll see later.)
回到我凌乱的办公室-我可能花几分钟来整理我所有的文件和垃圾,然后将它们放入贴有标签的盒子中。 如果我的妻子一直不得不去办公室取文件,或者如果我雇用某人和我一起在房间里工作,那么对我所有人来说,使我井井有条就很有好处。 没有人会问我在哪里可以找到东西,而且我可能仍然可以很容易地找到东西。 另外,随着我雇用越来越多的人,我将从保持办公室有条不紊中获得越来越多的收益。 我什至可以让人们致力于在特定盒子中处理文档。 或者,如果我想将我所有的税收文件发送给我的纳税人,那么我可以将标签为“ Tax Stuff”的框发送给他/她,而不是试图四处搜集所有不同的文件。一团糟。 (我使用这些示例是有原因的-您稍后会看到。)
Could I have 10 people working in a messy office? Yes, it's POSSIBLE, but it's definitely not AS easy and simple as having them all work in an organized office.
我能在一个杂乱的办公室里有10个人吗? 是的,这是可能的,但绝对不像让它们都在有组织的办公室中工作那样容易和简单。
SO, the moral of this story is that it's sometimes good to spend a little more time at the beginning and write a little more code to save you a LOT of time later on. It's simply good planning so you can be more lazy later.
所以,这个故事的寓意是,有时花一些时间在开始时写一些更多的代码来节省您以后的时间,这是很好的。 这只是一个很好的计划,因此您以后可以更加懒惰。
Let me bring those office examples back to the technical world. Despite some additional code in the beginning, there are several reasons for object-oriented code:
让我将这些办公示例带回技术领域。 尽管开始时有一些其他代码,但还是有一些使用面向对象代码的原因:
Easier to maintain as code grows.
随着代码的增长,易于维护。
Easier to document.
易于记录。
Easier for others to learn.
易于他人学习。
More portable (for selling, sharing, or reusing code)
更具可移植性(用于销售,共享或重用代码)
面向对象的编程:如何做 (Object-Oriented Programming: How to Do It)
OOP PHP编程的最基本元素是“类”。 一个类如下所示:class House {
}
To make use of your House class, you simply create an "instance" of it by using the "new" command, like this:
要使用您的House类,您只需使用“ new”命令创建它的“实例”,如下所示:
$yourHouse = new House();
$yourHouse = new House();
$myHouse = new House();
类属性 (Class Properties)
没有任何定义或识别特征,$ yourHouse和$ myHouse之间确实没有区别。 因此,我们通过指定邮寄地址来进一步定义房屋。 首先,我们需要更新我们的类定义,以便它可以容纳邮件地址:class House {
public $mailingAddress = "123 Default Address Street";
public $numberBedrooms = 2;
}
Don't worry about what "public" means for now - just use it in front of your class properties. You can probably guess that the "123 Default Address Street" is the default value for this property, and 2 is the default value for $numberBedrooms.
现在不必担心“公共”的含义-只需在类属性前面使用它即可。 您可能会猜到“ 123默认地址街道”是此属性的默认值,而2是$ numberBedrooms的默认值。
So now when we create instances called $yourHouse and $myHouse, both of them automatically come with the mailing address "123 Default Address Street" and 2 bedrooms. Now, there are a lot of houses that have 2 bedrooms, so the default value could be handy here, but every house has a different address, so having a default address probably isn't necessary, so let's just take it out:
因此,现在当我们创建名为$ yourHouse和$ myHouse的实例时,它们都自动带有邮件地址“ 123 Default Address Street”和2个卧室。 现在,有很多房子有2间卧室,因此默认值在这里很方便,但是每个房子都有一个不同的地址,因此可能没有必要使用默认地址,因此我们将其删除:
class House {
public $mailingAddress;
public $numberBedrooms = 2;
}
$yourHouse = new House();
$yourHouse->mailingAddress = "123 Your Street";
$myHouse = new House();
$myHouse->mailingAddress = "444 My Street";
$instance_variable->property_name = value;
$myHouse = new House();
$myHouse->mailingAddress = "444 My Street";
echo $myHouse->mailingAddress; // Will display "444 My Street"
echo $myHouse->numberBedrooms; // Will display "2"
类方法 (Class Methods)
这就是您需要了解的基本类属性的全部信息,但是类的真正内容是在“方法”类中,这些方法只是在类内部定义的函数,如下所示:class House {
// Our Class Properties
public $mailingAddress;
public $numberBedrooms = 2;
// Our Class Methods
public function cleanTheHouse()
{
for($i = 1; $i <= $this->numberBedrooms; $i++)
{
echo "Cleaning bedroom " . $i;
}
}
}
So what if YOUR house had 10 rooms and mine had 5? How would this function know how many rooms to clean? The secret is in the $this keyword. The $this keyword references the current instance, no matter if it's $yourHouse or $myHouse. So if I created this code:
那么,如果您的房子有10个房间而我的房子有5个房间怎么办? 此功能如何知道要打扫多少个房间? 秘密在$ this关键字中。 $ this关键字引用当前实例,而不管它是$ yourHouse还是$ myHouse。 因此,如果我创建此代码:
$yourHouse = new House();
$yourHouse->numberBedrooms = 10;
$yourHouse->cleanTheHouse();
$myHouse = new House();
$myHouse->numberBedrooms = 5;
$myHouse->cleanTheHouse();
Then $yourHouse would have a loop that cleaned 10 bedrooms, while $myHouse would have 5 rooms cleaned. The $this keyword is one of the most useful tools you'll have when creating class methods, because it allows you to reference properties ONLY for the current instance of that class. If I didn't have $this, then I wouldn't know how many bedrooms to clean! If I guessed 10, then it might work for $yourHouse, but that would be wrong for $myHouse, which only has 5 bedrooms.
然后$ yourHouse会有一个循环,可以清洗10间卧室,而$ myHouse可以清洗5个房间。 $ this关键字是创建类方法时将拥有的最有用的工具之一,因为它允许您仅引用该类的当前实例的属性。 如果我没有这个,那我就不知道要打扫多少间卧室! 如果我猜为10,那么它可能适用于$ yourHouse,但是对于只有5间卧室的$ myHouse来说是错误的。
Let's add one last class method that uses an argument and returns a value:
让我们添加一个使用参数并返回值的最后一类方法:
class House {
// Our Class Properties
public $mailingAddress;
public $numberBedrooms = 2;
// Our Class Methods
public function cleanTheHouse()
{
for($i = 1; $i <= $this->numberBedrooms; $i++)
{
echo "Cleaning bedroom " . $i;
}
}
public function hasMoreThanRooms($numRooms)
{
if($this->numberBedrooms > $numRooms)
{
return true;
}
else
{
return false;
}
}
}
$yourHouse = new House();
$yourHouse->numberBedrooms = 10;
if($yourHouse->hasMoreThanRooms(8))
{
print "Your house has more than 8 rooms? Wow.";
}
else
{
print "You don't have more than 8 bedrooms? Where am I supposed to sleep?";
}
$myHouse = new House();
$myHouse->numberBedrooms = 5;
if($myHouse->hasMoreThanRooms(4))
{
print "My house has more than 4 rooms? Wow.";
}
else
{
print "I don't have more than 4 bedrooms? Where are you supposed to sleep?";
}
The result of running this is:
运行此命令的结果是:
Your house has more than 8 rooms? Wow.
您的房子有8个以上的房间? 哇。
My house has more than 4 rooms? Wow.
我的房子有四个以上的房间? 哇。
范围:公共和私人 (Scope: Public and Private)
说到房屋,每座房屋都有内部和外部,对吗? 如果您的浴室里有镜子,那么房子外面的人很有可能看不到镜子。 大多数房屋的外部都有窗户,室内或室外的任何人都可以看到该窗户。 具有仅在您的家庭私密中可见的某些事物(私有)和任何人(公共)可见的某些事物的整个概念-整个概念称为“范围”,它是有关类的最后一个重要的基本知识。Whenever we've created class properties or methods with "public" in front of their names, we've been declaring them to be visible to any code inside or outside of the class. It might help to visualize the different code locations:
只要我们在类属性或方法的名称前面加上“ public”,便会声明它们对于类内部或外部的任何代码均可见。 可能有助于可视化不同的代码位置:
class House {
public $window = "clear";
private $bathroomMirror = "shiny";
// Inside the class - code in here can access the values
// of $window AND $bathroomMirror
public function doSomething()
{
echo $this->window; // Will show "clear"
echo $this->bathroomMirror; // Will show "shiny"
echo $this->runSecretFormula(); // Will show "Hello world!";
}
private function runSecretFormula()
{
return "Hello world!";
}
}
// Outside the class - code here can only access the value of $window.
// Trying to access $bathroomMirror from here would not work.
$myHouse = new House();
echo $myHouse->window; // Will show "clear"
echo $myHouse->bathroomMirror; // OH NO! Will give you a big, fat, fatal error if you try to run the script!
echo $myHouse->runSecretFormula(); // OH NO! Will also give you an error!
There are a variety of opinions on when and where you should use private/public functions. It's very common for programmers new to OOP to just use "public" for everything, since it doesn't really have any limits. So why use private at all?
关于何时何地应使用私有/公共功能有多种意见。 对于刚接触OOP的程序员来说,对所有内容都使用“ public”是很常见的,因为它实际上没有任何限制。 那么为什么要完全使用private?
For me, it really comes down to security. I always assume the worst when I'm programming, and I assume that a hacker will figure out a way to run some PHP code on my system. If I have a super-secret password inside of a class property, then I certainly don't want to make it easy for a hacker to run some code that echoes that password and gets it! If I make it private, then if the hacker tries to echo it, then he/she will just get an error!
对我而言,这实际上取决于安全性。 在编程时,我总是假设最糟糕的情况,并且我假设黑客会找出一种在系统上运行某些PHP代码的方法。 如果我在类属性中有一个超级秘密的密码,那么我当然不想让黑客轻松运行一些回显该密码并获取密码的代码! 如果我将其设为私有,那么如果黑客试图回显它,那么他/她将只会得到一个错误!
You might be saying to yourself, "But if a hacker could run PHP code, then he/she could probably just use PHP functions to show the source code of the class and see the password!" You would be right, but there are ways to help protect against that. For example, there are many PHP script compilers out there that will turn your source code into machine language (which actually runs faster). So by using a combination of compilation and private methods/properties, you can make it very difficult for hackers to gain access to code and properties that should be kept... well... private.
您可能对自己说:“但是,如果黑客可以运行PHP代码,那么他/她可能仅使用PHP函数来显示该类的源代码并查看密码!” 您是正确的,但是有一些方法可以防止这种情况的发生。 例如,有许多PHP脚本编译器可以将您的源代码转换为机器语言(实际上运行速度更快)。 因此,通过结合使用编译和私有方法/属性,可以使黑客很难访问应保留的代码和属性。
In addition to private and public scopes, there is also a scope called "protected", but that will be covered in my advanced OOP article, when we talk about extending classes.
除了私有和公共作用域之外,还有一个称为“保护”的作用域,但是当我们谈论扩展类时,将在我的高级OOP文章中进行介绍。
For now, these are all the basics you need to know about how to create and use a USEFUL class. Thanks for reading!
目前,这些都是您需要了解的有关如何创建和使用USEFUL类的所有基础知识。 谢谢阅读!
翻译自: https://www.experts-exchange.com/articles/2626/Beginning-Object-Oriented-Programming-in-PHP.html
php面向对象编程