我正在处理类和对象类结构,但不是在复杂的级别——只是类和函数,然后在一个地方进行实例化.
I am working with classes and object class structure, but not at a complex level – just classes and functions, then, in one place, instantiation.
关于__construct
和__destruct
,请简单的告诉我:构造函数和析构函数的目的是什么?
As to __construct
and __destruct
, please tell me very simply: what is the purpose of constructors and destructors?
我知道学校水平的理论解释,但我期待在现实世界中类似的东西,比如我们必须在哪些情况下使用它们.
I know the school level theoretical explanation, but i am expecting something like in real world, as in which situations we have to use them.
请提供一个例子.
问候
构造函数是在对象初始化(其内存分配、实例属性复制等)后执行的函数.其目的是使对象处于有效状态.
A constructor is a function that is executed after the object has been initialized (its memory allocated, instance properties copied etc.). Its purpose is to put the object in a valid state.
通常,要处于可用状态的对象需要一些数据.构造函数的目的是在实例化时强制将此数据提供给对象,并禁止任何没有此类数据的实例.
Frequently, an object, to be in an usable state, requires some data. The purpose of the constructor is to force this data to be given to the object at instantiation time and disallow any instances without such data.
考虑一个简单的类,它封装了一个字符串并有一个返回这个字符串长度的方法.一种可能的实现是:
Consider a simple class that encapsulates a string and has a method that returns the length of this string. One possible implementation would be:
class StringWrapper {
private $str;
public function setInnerString($str) {
$this->str = (string) $str;
}
public function getLength() {
if ($this->str === null)
throw new RuntimeException("Invalid state.");
return strlen($this->str);
}
}
为了处于有效状态,此函数需要在 getLength
之前调用 setInnerString
.通过使用构造函数,您可以在调用 getLength
时强制所有实例处于良好状态:
In order to be in a valid state, this function requires setInnerString
to be called before getLength
. By using a constructor, you can force all the instances to be in a good state when getLength
is called:
class StringWrapper {
private $str;
public function __construct($str) {
$this->str = (string) $str;
}
public function getLength() {
return strlen($this->str);
}
}
您还可以保留 setInnerString
以允许在实例化后更改字符串.
You could also keep the setInnerString
to allow the string to be changed after instantiation.
当对象即将从内存中释放时,会调用析构函数.通常,它包含清理代码(例如,关闭对象所持有的文件描述符).它们在 PHP 中很少见,因为 PHP 会在脚本执行结束时清除脚本持有的所有资源.
A destructor is called when an object is about to be freed from memory. Typically, it contains cleanup code (e.g. closing of file descriptors the object is holding). They are rare in PHP because PHP cleans all the resources held by the script when the script execution ends.
这篇关于PHP 构造函数的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!