php从空值创建默认对象?

Ada*_*han 7 php model-view-controller standards

好吧,我想要做的是制作一些东西,所以我可以称之为 $this->model->users->getInfomation('name');或类似于我的框架上的similer但是php给我一个严格的标准从空值创建默认对象

protected function model($model)
{
    $path = "features". DS ."models". DS . $model .".php";
    require $path;

    $class = 'Model'. ucfirst($model);
    $this->model->$model = new $class;
}
Run Code Online (Sandbox Code Playgroud)

我们可以做到这样它会以某种方式符合标准吗?

编辑*

这个函数在类Application中,所以我可以从我们的控制器扩展它们,比如博客扩展应用程序,然后调用像$ this-> model-> blog这样的东西就像我上面做的那样,当我做类似的事情时

protected function model($model)
{
    $path = "features". DS ."models". DS . $model .".php";
    require $path;

    $class = 'Model'. ucfirst($model);
    $this->$model = new $class;
}
Run Code Online (Sandbox Code Playgroud)

是的,上面的代码工作正常 $this->blog->getSomething();,但不知何故,我想让他们在一个组,如上面的问题,所以如果我们想得到类似的东西$this->model->blog->getSomething();

谢谢你的时间.

亚当拉马丹

Ber*_*rak 7

单独使用该代码很难看出你实际上在做错什么.我已经制作了一些非常简单的代码来重现错误:

<?php
$bar = 42;
$foo = null;

$foo->bar = $bar;
Run Code Online (Sandbox Code Playgroud)

它发出此警告的原因是您将值指定为"对象方式",但是您将其分配给不是对象的变量.通过这样做,Zend引擎实际上为$ foo创建了一个对象,它是StdClass的一个实例.显然,10次中有9次,这不是你想要做的,所以PHP提供了一个有用的信息.

在你的情况下:$ this-> model不是一个对象(还).如果你想摆脱错误,只需:

if( !is_object( $this->model ) ) {
    $this->model = new StdClass;
}
$this->model->$model = new $class;
Run Code Online (Sandbox Code Playgroud)

干杯.