php从空值创建默认对象?

时间:2011-02-01 08:02:24

标签: php model-view-controller standards

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

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

    $class = 'Model'. ucfirst($model);
    $this->model->$model = new $class;
}

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

编辑*

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

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

    $class = 'Model'. ucfirst($model);
    $this->$model = new $class;
}

是的,上面的代码工作得很好 $this->blog->getSomething();,但不知怎的,我想把它们放在一个组中,就像上面的问题一样,所以如果我们想得到像{{1}这样的东西}

感谢您的时间。

Adam Ramadhan

5 个答案:

答案 0 :(得分:7)

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

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

$foo->bar = $bar;

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

在您的情况下:$ this-&gt;模型不是对象(尚未)。如果你想摆脱错误,只需:

if( !is_object( $this->model ) ) {
    $this->model = new StdClass;
}
$this->model->$model = new $class;

干杯。

答案 1 :(得分:2)

您必须使用__get魔法 - http://php.net/manual/pl/language.oop5.magic.php

你可以实现你想做的事情:

<?php
class ModelCreator
{
    private $_modelsCreated = array();
    public function __get($model)
    {
        $class = 'Model'. ucfirst($model);
        //avoid creating multiple same models
        if (!array_key_exists($model, $this->_modelsCreated)) {
            $path = "features". DS ."models". DS . $model .".php";
            require_once 'modeluser.php';
            $this->_modelsCreated[$class] = new $class;
        }
        return $this->_modelsCreated[$class];
    }
}

class MyClass
{
    private $_model;

    public function __construct(ModelCreator $model)
    {
        $this->_model = $model;
    }

    public function __get($name) 
    {
        if ($name === 'model') {
            return $this->_model;
        }
    }
}  

$myClass = new MyClass(new ModelCreator());
$userModel = $myClass->model->user; // will return a class of ModelUser

但你应该避免像上面那样的魔法 - &gt;更好的方法是这样做:

//model creator is an instance of model creator
$this->modelCreator->getModel('user'); // now you know what exactly is happening

答案 2 :(得分:0)

必须使用双$'s

$this->model->$$model = new $class;

答案 3 :(得分:0)

除了Berry Langerak的回答

is_object仍将触发严格检查,因为它假设$ this-&gt;模型中存在“某些内容”。 isset是一种更好的方法

if( !isset( $this->model ) ) {
    $this->model = new StdClass;
}

$this->model->$model = new $class;

答案 4 :(得分:0)

SELECT APPROX_TOP_COUNT(x, 2) as approx_top_count
FROM UNNEST(["apple", "apple", "pear", "pear", "pear", "banana"]) as x;

+-------------------------+
| approx_top_count        |
+-------------------------+
| [{pear, 3}, {apple, 2}] |
+-------------------------+
相关问题