PHP构造函数的用途 [英] Purpose of PHP constructors

查看:177
本文介绍了PHP构造函数的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用类和对象类结构,但不是在复杂的层次 - 只是类和函数,然后,在一个地方,实例化。

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 ,请告诉我:构造函数和析构函数的用途

我知道学校层面的理论解释,但我期望在现实世界中,我们必须使用它们。

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构造函数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆