类构造函数的正确语法[重复]

问题描述 投票:0回答:1

我想知道这个语法在 php8.3 中是否正确:


class cpm {

    // Constructor gets initiated with userid
    function cpm($user,$date="d.m.Y - H:i") {
        // defining the given userid to the classuserid
        $this->userid = $user; 
        
        
        // Define that date_format
        $this->dateformat = $date;
        
        //we initiate with new messages
        //$this->getmessages(0); 
        //we get the email
    $this->useremail = $this->getemail($this->userid);
        //printf("email es   : %s\n", $useremail); 
        //we get the possible receivers;
    $this->getMessageReceivers();
    }

...

我认为不是,因为当我传递参数时:

$pm = new cpm(1010); // 1010 is just an example of user id

事实证明 $this->userid 没有收到值 1010

我期望 $this->userid 等于 1010。

php class constructor
1个回答
2
投票

在 PHP 8.3 中,应该使用

__construct()
而不是类名来声明构造函数。虽然 PHP 历史上允许使用构造函数的类名,但使用
__construct()
被认为是最佳实践。

这是代码的更正版本:

class cpm {
    // Constructor gets initiated with userid
    function __construct($user, $date = "d.m.Y - H:i") {
        // defining the given userid to the classuserid
        $this->userid = $user; 
        
        // Define that date_format
        $this->dateformat = $date;
        
        //we initiate with new messages
        //$this->getmessages(0); 
        //we get the email
        $this->useremail = $this->getemail($this->userid);
        //printf("email es   : %s\n", $useremail); 
        //we get the possible receivers;
        $this->getMessageReceivers();
    }
    
    // Other methods here...
}

通过使用

__construct()
,当您使用
cpm
创建
$pm = new cpm(1010);
类的新实例时,
$this->userid
确实应该如您所期望的那样等于 1010。如果它没有按预期工作,则代码中的其他地方可能存在问题。确保
getemail()
方法返回预期值,并且代码中没有其他部分可能会干扰设置
userid
属性。

© www.soinside.com 2019 - 2024. All rights reserved.