php 致命错误:不在对象上下文中使用 $this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1643931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:22:18  来源:igfitidea点击:

Fatal error: Using $this when not in object context

phpoopfatal-error

提问by designer-trying-coding

here is the part if having error.

如果有错误,这里是部分。

Fatal error: Using $this when not in object context in /pb_events.php on line 6

致命错误:在第 6 行的 /pb_events.php 中不在对象上下文中时使用 $this

line 6 is: $jpp = $this->vars->data["jpp"];

第 6 行是: $jpp = $this->vars->data["jpp"];

function DoEvents($this) {

    global $_CONF, $_PAGE, $_TSM , $base;

    $jpp = $this->vars->data["jpp"];

    $cache["departments"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_departments]}");
    $cache["locations"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_location]}");
    $cache["names"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_names]}");
    $cache["categories"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_categories]}");

Thanks a lot! appreciate!

非常感谢!欣赏!

回答by user187291

$this only makes sense in methods, not in functions

$this 只在方法中有意义,在函数中没有意义

this is ok

还行吧

class Foo {
     function bar() {
          $this->...

this is not

这不是

function some() {
    $this->

// edit: didn't notice he passes "$this" as parameter

// 编辑:没有注意到他将“$this”作为参数传递

advice: simply replace "$this" with "$somethingElse"

建议:只需将“$this”替换为“$somethingElse”

回答by Jeff Ober

You cannot pass $thisto a procedural function. $thisis a reserved variable.

您不能传递$this给过程函数。$this是一个保留变量。

回答by Michal M

As per my comments. You want to use $thisas passed variable and php doesn't allow it outside class methods body.

根据我的评论。您想使用$this作为传递的变量,而 php 不允许在类方法主体之外使用它。

function DoEvents($obj) {

    global $_CONF, $_PAGE, $_TSM , $base;

    $jpp = $obj->vars->data["jpp"];

    $cache["departments"] = $obj->db->QFetchRowArray("SELECT * FROM {$obj->tables[job_departments]}");
    $cache["locations"] = $obj->db->QFetchRowArray("SELECT * FROM {$obj->tables[job_location]}");
    $cache["names"] = $obj->db->QFetchRowArray("SELECT * FROM {$obj->tables[job_names]}");
    $cache["categories"] = $obj->db->QFetchRowArray("SELECT * FROM {$obj->tables[job_categories]}");

回答by dnagirl

You have to make the object first.

你必须先制作对象。

   $object=new Myobject;
   DoEvents($object);