PHP 中的类是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2206387/
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
What is a class in PHP?
提问by Strawberry
I'm having serious issues understanding PHP classes from a book. They seem very difficult. What is their purpose and how do they work?
我在从书中理解 PHP 类时遇到了严重的问题。他们似乎非常困难。它们的目的是什么,它们是如何工作的?
回答by Gordon
In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
简而言之,类是对象的蓝图。一个对象封装了应用程序中某些概念上相关的状态和职责,并且通常提供一个编程接口来与之交互。这促进了代码重用并提高了可维护性。
Imagine a Lock:
想象一把锁:
namespace MyExample;
class Lock
{
private $isLocked = false;
public function unlock()
{
$this->isLocked = false;
echo 'You unlocked the Lock';
}
public function lock()
{
$this->isLocked = true;
echo 'You locked the Lock';
}
public function isLocked()
{
return $this->isLocked;
}
}
Ignore the namespace, privateand publicdeclaration right now.
现在忽略namespace,private和public声明。
The Lock class is a blueprint for all the Locks in your application. A Lock can either be lockedor unlocked, represented by the property$isLocked. Since it can have only these two states, I use a Boolean (trueor false) to indicate which state applies. I can interact with the Lock through it's methodslockand unlock, which will change the state accordingly. The isLockedmethod will give me the current state of the Lock. Now, when you create an object (also often referred to as an instance) from this blueprint, it will encapsulate unique state, e.g.
Lock 类是应用程序中所有锁的蓝图。Lock 可以被锁定或解锁,由属性表示$isLocked。由于它只能有这两种状态,因此我使用布尔值 (true或false) 来指示应用哪种状态。我可以通过它的方法lock和Lock 与 Lock 交互unlock,这将相应地改变状态。该isLocked方法会给我锁的当前状态。现在,当你从这个蓝图中创建一个对象(通常也称为实例)时,它会封装唯一的状态,例如
$aLock = new Lock; // Create object from the class blueprint
$aLock->unlock(); // You unlocked the Lock
$aLock->lock(); // You locked the Lock
Let's create another lock, also encapsulating it's own state
让我们创建另一个锁,也封装它自己的状态
$anotherLock = new Lock;
$anotherLock->unlock(); // You unlocked the Lock
but because each object/instance encapsulates it's own state, the first lock stays locked
但是因为每个对象/实例都封装了它自己的状态,所以第一个锁保持锁定状态
var_dump( $aLock->isLocked() ); // gives Boolean true
var_dump( $anotherLock->isLocked() ); // gives Boolean false
Now the entire reponsibility of keeping a Lock either locked or unlocked is encaspulated within the Lock class. You don't have to rebuilt it each time you want to lock something and if you want to change how a Lock works you can change this in the blueprint of Lock instead of all the classes havinga Lock, e.g. a Door:
现在,保持 Lock 锁定或解锁的全部责任都包含在 Lock 类中。您不必每次想要锁定某些东西时都重新构建它,如果您想更改 Lock 的工作方式,您可以在 Lock 的蓝图中进行更改,而不是所有类都具有Lock,例如 Door:
class Door
{
private $lock;
private $connectsTo;
public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->connectsTo = 'bedroom';
}
public function open()
{
if($this->lock->isLocked()) {
echo 'Cannot open Door. It is locked.';
} else {
echo 'You opened the Door connecting to: ', $this->connectsTo;
}
}
}
Now when you create a Door object you can assign a Lock object to it. Since the Lock object handles all the responsibility of whether something is locked or unlocked, the Door does not have to care about this. In fact any objects that can use a Lock would not have to care, for instance a Chest
现在,当您创建一个 Door 对象时,您可以为其分配一个 Lock 对象。由于 Lock 对象负责处理某物是否被锁定或解锁的所有责任,因此 Door 不必关心这个。事实上,任何可以使用 Lock 的对象都不必关心,例如 Chest
class Chest
{
private $lock;
private $loot;
public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->loot = 'Tons of Pieces of Eight';
}
public function getLoot()
{
if($this->lock->isLocked()) {
echo 'Cannot get Loot. The chest is locked.';
} else {
echo 'You looted the chest and got:', $this->loot;
}
}
}
As you can see, the reponsibility of the Chest is different from that of a door. A chest contains loot, while a door separates rooms. You could code the locked or unlocked state into both classes, but with a separate Lock class, you don't have to and can reuse the Lock.
如您所见,宝箱的职责与门的职责不同。一个箱子包含战利品,而一扇门将房间隔开。您可以将锁定或解锁状态编码到两个类中,但是使用单独的 Lock 类,您不必并且可以重用 Lock。
$doorLock = new Lock;
$myDoor = new Door($doorLock);
$chestLock = new Lock;
$myChest new Chest($chestLock);
Chest and Door now have their unique locks. If the lock was a magical lock that can exist in multiple places at the same time, like in Quantum physics, you could assign the same lock to both chest and door, e.g.
宝箱和门现在拥有独特的锁。如果锁是一个可以同时存在于多个地方的魔法锁,比如在量子物理学中,你可以为箱子和门分配相同的锁,例如
$quantumLock = new Lock;
$myDoor = new Door($quantumLock);
$myChest new Chest($quantumLock);
and when you unlock()the $quantumLock, both Door and Chest would be unlocked.
当你unlock()的$quantumLock,门和胸部都将被解锁。
While I admit Quantum Locks are a bad example, it illustrates the concept of sharing of objects instead of rebuilding state and responsibility all over the place. A real world example could be a database object that you pass to classes usingthe database.
虽然我承认量子锁是一个不好的例子,但它说明了共享对象的概念,而不是到处重建状态和责任。一个真实的例子可能是一个你使用数据库传递给类的数据库对象。
Note that the examples above do not show how to get to the Lock of a Chest or a Door to use the lock()and unlock()methods. I leave this as an exercise for your to work out (or someone else to add).
请注意,上面的示例并未显示如何使用lock()和unlock()方法到达箱子或门的锁。我将此作为练习供您解决(或其他人添加)。
Also check When to use self over $this?for a more in-depth explanation of Classes and Objects and how to work with them
还要检查何时在 $this 上使用 self?更深入地解释类和对象以及如何使用它们
For some additional resources check
对于一些额外的资源检查
回答by Ondrej Slinták
I know you asked for a resource, not an explanation, but here's something by what I understood basic implementation of classes:
我知道你要的是资源,而不是解释,但这是我对类的基本实现的理解:
Imagine class as a template of building. A basic sketch how a building should look like. When you are going to actually build it, you change some things so it looks like your client wants (properties in case of class). Now you have to design how things inside of the building are going to behave (methods). I'm going to show it on a simple example.
把班级想象成建筑的模板。建筑应该是什么样子的基本草图。当您要实际构建它时,您会更改一些内容,使其看起来像您的客户想要的(属性在class 的情况下)。现在您必须设计建筑物内的事物将如何表现(方法)。我将用一个简单的例子来展示它。
Building class:
建筑类:
/**
* Constructs a building.
*/
class Building
{
private $name;
private $height;
public function __construct( $name, $height )
{
$this->name = $name;
$this->height = $height;
}
/**
* Returns name of building.
*
* @return string
*/
public function getName( )
{
return $this->name;
}
public function elevatorUp( )
{
// Implementation
}
public function elevatorDown( )
{
// Implementation
}
public function lockDoor( )
{
// Implementation
}
}
Calling the class:
调用类:
// Empire State Building
$empireStateBuilding = new Building( "Empire State Building", 381 );
echo $empireStateBuilding->getName( );
$empireStateBuilding->lockDoor( );
// Burj Khalifa
$burjKhalifa = new Building( "Burj Khalifa", 828 );
echo $burjKhalifa->getName( );
$burjKhalifa->lockDoor( );
Just copy it, run it on your localhost and try to do some changes. In case of any questions, just ask me. If you don't find this useful, just use links of previous posters, those are pretty solid tutorials.
只需复制它,在本地主机上运行它并尝试进行一些更改。如有任何问题,尽管问我。如果您觉得这没有用,只需使用以前海报的链接,这些都是非常可靠的教程。
回答by Jaya Wijaya
To offer a view from another angle if I may please (based on personal experience). You need to feel "the need of OOP" before you can actually understand what is it all about - IMHO, learning resources should come after this.
如果可以的话,从另一个角度提供一个观点(基于个人经验)。在您真正了解它的全部内容之前,您需要感受到“OOP 的需要” - 恕我直言,学习资源应该在此之后。
One would basically "need" to be stuck in structural difficulties when writing relatively large piece of software written in procedural style (as opposed to Object Oriented, sorry if anyone disagree with the term). By then, he/she could try restructuring the code into objects to better organize it and, naturally, learn more about OOP in detail. Again, this is my personal experience and it brought me into understanding faster than any book.
在编写以程序风格编写的相对较大的软件时,人们基本上“需要”陷入结构困境(与面向对象相反,如果有人不同意这个术语,抱歉)。到那时,他/她可以尝试将代码重组为对象以更好地组织它,并且自然而然地详细了解 OOP。同样,这是我的个人经历,它比任何一本书都让我更快地理解。
Just my two cents.
只有我的两分钱。
回答by Deepak Syal
Classes are the blueprints of objects.There is the name of the Caris class. We are define the variable and method in the class.Class is define with the curly braces.Inside the curly braces you can define the variable, method, Properties and function. Function and Method Both are the same.You can define the method and variable is the class curly braces as per your requirements.
类是对象的蓝图。有汽车的名字是类。我们在类中定义变量和方法。类是用花括号定义的。花括号里面可以定义变量、方法、属性和函数。函数和方法都是一样的。你可以根据你的要求定义方法和变量是类花括号。
class car{
类车{
}
}
foreach(get_declared_classes()as $class){
foreach( get_declared_classes()作为 $class){
echo ($class)."<br>";
}
}
get_declared_classes()is an predefined function in php.It returns an array of the names of the declared classes.
get_declared_classes()是php中的一个预定义函数。它返回一个声明类名称的数组。


