使用构造函数的好处? [英] Benefits of using a constructor?

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

问题描述

在我试图在PHP中了解更多关于OOP的任务。我已经碰到了构造函数很多次,根本不能忽略它。在我的理解,构造函数被调用时,我创建一个对象,这是正确的吗?



但是为什么我需要创建这个构造函数,如果我可以使用normal

解决方案



$ b

div>

是在创建对象时调用构造函数。



构造函数的有用性的一个小例子是



class Bar
{
//我们将在类中使用的变量
var $ val;

//当有人执行$ foo = new Bar()时调用此函数;
//但是这个构造函数在其定义中还有一个$ var,
//所以你必须做$ foo = new Bar(some data)
function __construct($ var)
{
//将构造函数中的$ var赋值给$ val变量
//我们在上面定义
$ this-> val = $ var
}
}

$ foo = new Bar(baz);

echo $ foo-> val // baz

//你也可以这样看到类中定义的所有内容
print_r($ foo);

更新:
一个问题还问为什么要使用它,一个现实的例子是一个数据库类,其中调用对象的用户名和密码以及要连接到的表,构造函数将连接到该对象。然后你有功能来完成数据库中的所有工作。


In my quest in trying to learn more about OOP in PHP. I have come across the constructor function a good few times and simply can't ignore it anymore. In my understanding, the constructor is called upon the moment I create an object, is this correct?

But why would I need to create this constructor if I can use "normal" functions or methods as their called?

cheers, Keith

解决方案

Yes the constructor is called when the object is created.

A small example of the usefulness of a constructor is this

class Bar
{
    // The variable we will be using within our class
    var $val;

    // This function is called when someone does $foo = new Bar();
    // But this constructor has also an $var within its definition,
    // So you have to do $foo = new Bar("some data")
    function __construct($var)
    {
        // Assign's the $var from the constructor to the $val variable 
        // we defined above
        $this->val = $var
    }
}

$foo = new Bar("baz");

echo $foo->val // baz

// You can also do this to see everything defined within the class
print_r($foo);

UPDATE: A question also asked why this should be used, a real life example is a database class, where you call the object with the username and password and table to connect to, which the constructor would connect to. Then you have the functions to do all the work within that database.

这篇关于使用构造函数的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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