2015-12-11 36 views
-1

问题是,即使类正在扩展PHP告诉我,我没有在正确的上下文中使用任何解决方案或解释?

我的代码:

<?php 

class MainController extends Controller 
{ 
    public $name = 'main'; 

    public function index($name) 
    { 
     $this->set('name', $name); 
     $this->renderPartial('main'); 
    } 
} 

的错误是

Fatal error: Using $this when not in object context in /home/wikizweb/www/wikizcms/admin/protected/controllers/MainController.php on line 9

+0

你可以显示你的代码运行会抛出错误? – wogsland

+1

我看到这个类,但是它的实例化或用法都没有。 – Flosculus

+0

有一个自动加载这些类,一个路由器类通过用户请求调用所有这些类 –

回答

0

在你的控制器功能:

public function index($name) 

假定您与请求发送参数 '名' 。根据您使用的框架以及设置路由的方式,名称可能是url的一部分。请添加您尝试匹配的网址路线以及您收到的实际错误。

而你的变量是公开的。尝试:

$this->name = $name; 

然后看看是否可以解决您的问题。

+0

对不起,但麻烦似乎是控制器类的实例化,因为当我使用一个变量实例化它工作正常,但是当通过扩展使用发生这个错误。 –

2

所以你的问题是这样的

Using $this when not in object context

或者,换一种说法,你不实例化类第一。你需要做这样的事情

$class = new MainController(); // class instance, with $this 
$class->index('Name'); 
+0

不知道为什么这是投下来的时候,它是正确的答案 – Edward

0

我解决了这个问题,接下来的说明描述或多或少是什么问题:

Please note, that when calling call_user_func_array() to redirect parameters between inherited classes, you should not use $this, because $this always refers to the class which has been instantiated. The following code even seems to crash PHP (PHP does not report error but the process simply terminates), because the the parameters are redirected only one level up (to class foo_bar2): http://php.net/manual/en/function.call-user-func-array.php

我使用的函数调用的行为我的应用程序,但我不能使用$这个,它看起来像静态方法,并且我解决了这个问题的实例化,并且为了解决这个问题,我在实例化类之前调用​​函数call_user_func_array()

相关问题