开发者

PHP non-client coder class execution

Simply question of theory

When building a class that is not going to be used by any other client-coders, what is the best method of execution? Consider the following:

class Test
{
    public function __construct()
    {
        $this->foo();
        $this->bar();
    }

    public function foo(){ //do something }

    public function bar(){ //do something }
}

$test = new Test;

As I know exactly what I want this class to do, and the order it should be done in, I simply call the functions during construction. However The same can be done by doing:

class Test
{
    public function __construct(){}

    public function foo(){ //do something }

    public function bar(){ //do something }
}

$test = new Test();
$test->foo();
$test->bar();

What are the advan开发者_如何学Gotages to doing it one way or the other? Be it performance, debugging, etc.

Edit

This is a general purpose question. Looking to hear all possibilities and concerns regarding these two ways of executing methods within a class.


In the 1st way you can make those functions private and use them only within the object itself.

class Test
{
    public function __construct()
    {
        $this->foo();
        $this->bar();
    }

    private function foo(){ //do something }

    private function bar(){ //do something }
}

$test = new Test; 
//so:
$test->foo(); //will throw an error

If you make the functions protected instead of private, any class that inherits from this class would be able to to use the functions (while still not allowing for the functions to be called on the outside)


With your second option, any object can call those functions outside the class definition, and depending on your code, you might not want that.


To elaborate on Neal's answer: If you can, make the functions private. That way, if you want to change them later, you know they are only used within their class.

So, to answer you question: The first answer is preferred because is makes your code easier to maintain. Performance wise, there is no difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜