PHP静态方法中调用非静态方法

一、前言

非静态方法可以调用静态方法,静态方法不可以调用非静态方法
因为:
   静态方法是属于类的,即静态方法是随着类的加载而加载的,在加载类时,程序就会为静态方法分配内存。
   非静态方法是属于对象的,对象是在类加载之后创建的。
   也就是说静态方法先于对象存在,当你创建一个对象时,程序为其分配内存,一般是通过this指针来指向该对象。静态方法不依赖于对象的调用,它是通过‘类名.静态方法名’这样的方式来调用的。而对于非静态方法,在对象创建的时候程序才会为其分配内存,然后通过类的对象去访问非静态方法。

二、代码

<?php

namespace app\index\controller;

class Abc {
    
    
    public function __construct() {
    
    

    }

    // index/abc/test
    public static function test() {
    
    
        //File:H:\\...\\application\\index\\controller\\Abc.php Line(11) Non-static method app\\index\\controller\\Abc::getUserInfo() should not be called statically
        //self::getUserInfo();

        //没问题
        $userInfo = (new self())->getUserInfo();

        //没问题
        $userInfo1 = (new Abc())->getUserInfo();
    }

    public function getUserInfo() {
    
    
        return [
            'id' => 1,
            'name' => '姓名',
            'is_vip' => 1,
        ];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/115025069