dqdmvg7332 2013-07-23 18:51
浏览 25
已采纳

在不使用构造函数的情况下分配新的类变量?

I want to know if I can somehow assign new variable without making constructor.

It seems pretty big overkill to create constructors on every class just to set initial private class variables.

Here is my example of what I want to achieve

<?php

class MyClass {
    public function DoSomething() {
        echo '1';
    }
}

class MySecondClass {
    private $obj = new MyClass(); // Error

    /*
        // This works, but I don't like it, I think it's total overkill
        function __construct() {
            $this->obj = new MyClass();
        }
    */

    public function PrintOne() {
        $this->obj->DoSomething();
    }
}

$class = new MySecondClass();
$class->PrintOne();

Just so it's perfectly clear here's the error message

syntax error, unexpected 'new' (T_NEW) on line 10

  • 写回答

2条回答 默认 最新

  • doujiu8479 2013-07-23 18:53
    关注

    You can't (that I know of), you need to either instantiate it in the constructor (Option A), or pass in the object (Option B).

    Option A:

    class MySecondClass {
        private $obj;
    
        function __construct() {
           $this->obj = new MyClass();
        }
    
        public function PrintOne() {
            $this->obj->DoSomething();
        }
    }
    

    Option B:

    class MySecondClass {
        private $obj;
    
        function __construct(MyClass $obj) {
           $this->obj = $obj;
        }
    
        public function PrintOne() {
            $this->obj->DoSomething();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?