2011-02-01 138 views
7

確定什麼即時試圖做的是makeing東西,所以我可以把它像 $this->model->users->getInfomation('name');什麼similer我的框架 但是PHP給我一個嚴格的標準創建默認的對象從空值php從空值創建默認對象?

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

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

我們可以做到這一點,它會以某種方式符合標準?

編輯*

這個功能是在課堂上的應用,所以我可以從我們的控制器 延長他們像博客擴展應用程序然後調用類似$這個 - >模型 - >博客將得到的東西像什麼IM上面做,當我這樣做

是上面的代碼工作正常$this->blog->getSomething();,但不知何故,我想讓他們在一組,像上面的問題,所以如果我們想要得到的東西像$this->model->blog->getSomething();

謝謝你的時間。

亞當·拉馬丹

+0

我真的不知道你想達到什麼目的。當你調用`$ this-> model - > [modelName]`時,你想要模型自動創建? – singles 2011-02-01 08:12:38

+0

是的,但問題可能是因爲$ this->模型是空的,我沒有做到這一點。不能我們只是補充說? – 2011-02-01 08:16:11

回答

7

很難看到你實際上做錯了單獨的代碼。我做了一些非常簡單的代碼來重現錯誤:

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

$foo->bar = $bar; 

它給出了這樣的警告的原因,是你要指定值「對象的方式」,但你將其分配給一個變量,不是一個對象。通過這樣做,Zend引擎實際上爲$ foo創建了一個對象,這是StdClass的一個實例。顯然,10次中的9次,這不是你想要做的,所以PHP提供了一個有用的信息。

在你的情況:$ this-> model不是一個對象(還)。如果你想擺脫錯誤,只要做:

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

乾杯。

0

必須使用雙$的

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

以及我知道$$意味着這樣$ this-> model - > $ blog?所以它給了我們一個$ blog不存在的錯誤。我在尋找的東西可以給我$ this-> model-> blog from $ this-> model - > $ model;但問題是$ this-> model,我沒有做任何事情。如果我錯了,請糾正我。 – 2011-02-01 08:15:04

+0

你在這個模型上沒有對象? – yoda 2011-02-01 08:16:43

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 

但是你應該避免魔法像上面 - >更好的辦法是這樣做的:

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

除了貝瑞Langerak的回答

is_object仍然將觸發嚴格檢查因爲它假設存在$這個 - 「東西」>模型。isset是更好的方法

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

$this->model->$model = new $class; 
相關問題