Laravel:Facade实际上会在调用方法上创建新对象吗? [英] Laravel: do facades actually create new objects on calling methods?

查看:79
本文介绍了Laravel:Facade实际上会在调用方法上创建新对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个演示类,通常通过

I have a demo class normally bound via

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

设置立面

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

类本身看起来像这样

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;
        }   

    }

有人告诉我,如果我要在此类上使用外观,Laravel会实例化该类的对象,然后在该对象上调用方法,例如:

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:

如果我做

Demo::setVal1('13654');

Demo::setVal2('random string')

我不应该使用Demo :: getVals()来检索刚刚创建的值,应该吗?由于每次使用立面方法时,都会实例化一个新对象,并且一个对象如何检索另一个对象的属性?应该有三个不同的实例,但是我仍然能够从其他实例中检索属性...

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...

我认为这只有在将类与App :: singleton而不是通过App :: bind绑定的情况下才有可能吗?

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

推荐答案

外观仍然只返回一个实例. 但是,您可以使用new static从方法中返回该类的新实例.

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

我在Laravel论坛上问,nesl247给出了很好的解释. 请在这里找到它: http://laravel.io/forum/08-22-2014-how-do-i-instantiate-a-new-object-by-calling-a-class-method-via-a -facade

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

这篇关于Laravel:Facade实际上会在调用方法上创建新对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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