drpph80800 2014-11-30 20:00
浏览 32
已采纳

php类变量交互

That's the problem, how can I call a class variable from a class function? Let me explain better:

    <?php

class Mine
{

    private $g = 'gg';
    const COSTANTE = 'valo';

    public static function sayHello()
    {
        echo self::COSTANTE;
        echo '<br>';
        echo $this->g;
    }
}
$h = new Mine();
$h->sayHello();
$h::sayHello();
?>

when I run this, it just print the constant COSTANTE.... Why it doesn't print the variable g?

  • 写回答

2条回答 默认 最新

  • dongwu9647 2014-11-30 20:41
    关注

    Turn on error reporting ( error_reporting ( E_ALL ); ), and you should receive the following error:

    Fatal error: Using $this when not in object context

    The pseudo-variable $this is a reference to the calling object, and is available from within an object context.

    self is used to access the current class, since static functions can be called without the actual object instance, when the method is called statically $this reference does not exists.

    A method declared as static can be accessed with an instantiated class object ( but it is always executed in a static context ), a property declared as static cannot.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致