当前位置:首页 > 后端 > php > 正文内容

php运行报错:Using $this when not in object context

hxing6418个月前 (01-07)php1206

php运行报错:Using $this when not in object context

以下是我的代码:

错误代码实例:

public static function getInfo() {
    // ... 省略部分代码
    $info = $this->getUser();
    return $info;
}
public function getUser() {
    return [
        'userName': => '小明',
        'age' => 17
    ];
}


原因分析:

getInfo是静态函数,$this无法使用,应该把getUser函数变成静态函数,或者把 getInfo 函数变成非静态函数


解决:

1. getUser 函数变成静态函数,$this使用self代替

public static function getInfo() {
    // ... 省略部分代码
    $info = self::getUser();
    return $info;
}
public static function getUser() {
    return [
        'userName': => '小明',
        'age' => 17
    ];
}


2. 把 getInfo 函数变成非静态函数

public function getInfo() {
    // ... 省略部分代码
    $info = $this->getUser();
    return $info;
}
public function getUser() {
    return [
        'userName': => '小明',
        'age' => 17
    ];
}


扫描二维码推送至手机访问。

版权声明:本文由星星博客发布,如需转载请注明出处。

本文链接:http://xingxinghan.cn/?id=505

分享给朋友:
返回列表

没有更早的文章了...

下一篇:php获取下个月,下一年此刻的时间戳

“php运行报错:Using $this when not in object context” 的相关文章

php获取下个月,下一年此刻的时间戳

获取当前时间戳:$now = time();获取下个月此刻的时间戳:$nextMonth = strtotime('+1 month');获取下一年此刻的时间戳$nextYear = strtotime('+1 year');...

php使用SplFileObject逐行读取CSV文件的高效方法

在PHP开发中,处理CSV文件是一项常见的任务。然而,如果CSV文件非常庞大,一次性将整个文件加载到内存中可能会导致内存溢出的问题。为了解决这个问题,我们可以使用PHP提供的SplFileObject类来逐行读取CSV文件,从而减少内存的占用。SplFileObject是PHP的一个内置类,它提供了...

php字符串压缩工具

判断字符串是否需要压缩,然后再进行压缩,需要优化的地方很多,比如把压缩结果保存起来,避免执行2次,判断是依赖于压缩的结果大小和原始字符串的大小来判断的,懒得处理了。代码如下/**  * 字符串压缩工具  */ class CompressStrUtil...

php es 报错 No alive nodes. All the 1 nodes seem to be down

php连接es时报错No alive nodes. All the 1 nodes seem to be down,原因是Elasticsearch开启了安全认证,查看服务器端响应信息为:received plaintext http traffic on&n...

php实现微信公众号扫码登录

php实现微信公众号扫码登录

服务器配置登录微信公众平台,左侧点开设置与开发 -> 基本设置,如图所示:设置好按照指示设置好配置,服务端代码如下:<?php // 微信token认证 $signature = $_GET["signature"]; $times...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。