Can I instantiate a PHP class inside another class?

前端 未结 8 818
挽巷
挽巷 2020-12-08 03:57

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 constructo

相关标签:
8条回答
  • 2020-12-08 04:45

    It's impossible to create a class in another class in PHP. Creating an object(an instance of a class) in another object is a different thing.

    0 讨论(0)
  • 2020-12-08 04:46

    This is possible in PHP 7 with Anonymous classes.

    See the example from the docs:

    class Outer
    {
        private $prop = 1;
        protected $prop2 = 2;
    
        protected function func1()
        {
            return 3;
        }
    
        public function func2()
        {
            return new class($this->prop) extends Outer {
                private $prop3;
    
                public function __construct($prop)
                {
                    $this->prop3 = $prop;
                }
    
                public function func3()
                {
                    return $this->prop2 + $this->prop3 + $this->func1();
                }
            };
        }
    }
    
    echo (new Outer)->func2()->func3();
    // Output: 6
    

    This is a simple example showing usage of anonymous classes, but not from within a class:

    // Pre PHP 7 code
    class Logger
    {
        public function log($msg)
        {
            echo $msg;
        }
    }
    
    $util->setLogger(new Logger());
    
    // PHP 7+ code
    $util->setLogger(new class {
        public function log($msg)
        {
            echo $msg;
        }
    });
    
    0 讨论(0)
提交回复
热议问题