You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP报错:Employee类Undefined property '$title'与'$get_title'(Intelephense 1014)

解决PHP中Employee类的"Undefined property"错误

你遇到的两个错误都是基础的面向对象语法问题,具体修正如下:

1. Undefined property '$title' 错误

在Employee类中,你在构造函数里给$this->title赋值,但没有提前声明这个属性。虽然PHP支持动态属性,但静态分析工具(比如Intelephense)会判定这是错误,同时也不符合类属性的声明规范。

修正方法:在Employee类里显式声明$title属性:

class Employee extends User {
    // 新增title属性声明
    public $title;

    public function __construct($name, $email, $password, $title)
    {
        parent::__construct($name, $email, $password);
        $this->title = $title;
    }
    public function get_title() {
        return $this->title;
    }
}

2. Undefined property '$get_title' 错误

最后一行的echo $employee1->get_title;是把方法当成属性访问了。get_title是类的方法,调用时必须加上括号(),否则PHP会把它当做一个不存在的属性来处理,从而报错。

修正方法:把调用改成方法形式:

echo $employee1->get_title();

完整修正后的代码

class User {
    // Properties are attributes that belong to a class
    public $name;
    public $email;
    public $password;

    public function __construct($name, $email, $password) {
        $this->name = $name;
        $this->email = $email;
        $this->password = $password;
    }

    function set_name($name) {
        $this->name = $name;
    }

    function get_name() {
        return $this->name;
    }
}

// Inheritence
class Employee extends User {
    public $title; // 声明title属性
    public function __construct($name, $email, $password, $title)
    {
        parent::__construct($name, $email, $password);
        $this->title = $title;
    }
    public function get_title() {
        return $this->title;
    }
}

$employee1 = new Employee('Sara', 'sara@gmail.com', '123', 'manager');
echo $employee1->get_title(); // 调用方法时加括号

执行修正后的代码,就能正常输出manager了。

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:01:35