我可以实例化另一个类中的PHP类吗? [英] Can I instantiate a PHP class inside another class?
本文介绍了我可以实例化另一个类中的PHP类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否允许在另一个类中创建一个类的实例。
I was wondering if it is allowed to create an instance of a class inside another class.
或者,我必须在外部创建它,然后传递通过构造函数?
Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.
示例(数据库类):
class some{
if(.....){
include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db
推荐答案
在另一个类中定义一个类。您应该包括类以外的其他类的文件。在你的情况下,这将给你两个顶级类 db
和一些
。现在在一些
的构造函数中,您可以决定创建一个 db
的实例。例如:
You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes db
and some
. Now in the constructor of some
you can decide to create an instance of db
. For example:
include SITE_ROOT . 'applicatie/' . 'db.class.php';
class some {
public __construct() {
if (...) {
$this->db = new db;
}
}
}
这篇关于我可以实例化另一个类中的PHP类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文