Laravel: do facades actually create new objects on calling methods?

喜你入骨 提交于 2019-12-10 15:32:55

问题


I have a demo class normally bound via

$this->app->bind('demo', function() { return new Demo(); }

An set up a facade

protected static function getFacadeAccessor() { return 'demo'; }

The class itself looks like this

class Demo 
    {

        private $value1;        
        private $value2;        

        public function setVal1($value)
        {
            $this->value1 = $value;
        }

        public function setVal2($value)
        {
            $this->value2 = $value;
        }

        public function getVals()
        {
            return 'Val 1: ' . $this->value1 . ' Val 2: ' . $this->value2;
        }   

    }

I was told that if I would use a facade on this class, Laravel would instantiate an object of the class and then call the method on that object, like:

$app->make['demo']->setVal1();     

Butt I tested some more and found this very strange (at least to me) behavior:

If I do

Demo::setVal1('13654');
and
Demo::setVal2('random string')

I shouldn't be able to use Demo::getVals() to retrieve the values I just created, should I? Since every time a facade method is used a new object will be instantiated and how can one object retrieve properties of another object? There should be three different instances but still I'm able to retrieve the properties from those other instances...

I thought this was only possible if one would bind the class with App::singleton and not via App::bind?


回答1:


The Facade still just returns one instance. You may however return new instances of the class using new static from a method.

I asked on Laravel Forum and nesl247 gave a quite good explanation. Please find it here: http://laravel.io/forum/08-22-2014-how-do-i-instantiate-a-new-object-by-calling-a-class-method-via-a-facade



来源:https://stackoverflow.com/questions/25307870/laravel-do-facades-actually-create-new-objects-on-calling-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!