Laravel中的withTest1($ a)和compact($ a)有什么区别? - php

我在Laravel中练习,并且找到了一个有用的方法“-> withVariable($ example)”,您可以在刀片文件中使用Variable作为$ variable名称。

我想问一下方法A和方法B之间是否有区别?

方法A

在控制器中:

$a = 'test a';
$b = 'test b';
$c = 'test c';

return view('welcome')->withTest1($a)->withTest2($b)->withTest3($c);

鉴于:

$test1 // test a
$test2 // test b
$test3 // test c

方法B

在控制器中:

$a = 'test a';
$b = 'test b';
$c = 'test c';

return view('welcome', compact('a', 'b', 'c'));

鉴于:

$a // test a
$b // test b
$c // test c

参考方案

显然,存在一些讨厌的代码可以实现这种行为,请参见Illuminate\View\View

    /**
     * Dynamically bind parameters to the view.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return \Illuminate\View\View
     *
     * @throws \BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        if (static::hasMacro($method)) {
            return $this->macroCall($method, $parameters);
        }

        if (! Str::startsWith($method, 'with')) {
            throw new BadMethodCallException(sprintf(
                'Method %s::%s does not exist.', static::class, $method
            ));
        }

        return $this->with(Str::camel(substr($method, 4)), $parameters[0]);
    }

因此,此__call方法捕获对视图实例的所有方法调用。
调用view()->withTest('abc')将导致$method = 'withTest',并最终级联到仅调用$this->with('test', 'abc')的最后一行。

因此最终结果没有区别。 withTest链看起来很讨厌。

恕我直言,这些魔术方法应该避免;像您已经使用的那样使用compact()表单,或者简单地使用:

view('myview', [
    'foo' => 123,
    'bar' => 'abc'
]);
// or
view('myview')->with([
    'foo' => 123,
    'bar' => 'abc'
]);
// or
$foo = 123;
$bar = 'abc';
view('myview', compact('foo', 'bar'));
// or
view('myview')->with(compact('foo', 'bar'));

可悲的是,有各种各样的可能性。

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…

PHP-从最后一个循环中删除逗号 - php

我在循环时有一个PHP,如果是最后一个循环,我想从,中删除​​最后一个逗号echo '],'; while($ltr = mysql_fetch_array($lt)){ echo '['; echo $ltr['days']. ' ,'. $ltr['name…

PHP Laravel从另一个驱动器读取文件 - php

我目前正在学习Laravel。我想知道是否有一种方法可以在Laravel中使用Storage::从另一个硬盘访问文件(使用Windows)。例如,我在驱动器C:上安装了带有Laravel的Xampp,但是我想访问网站目录之外的E:上的文件。我试过使用Storage::files('E:')和File::files('E:…