是否可以在 PHP 中将静态方法与非静态方法链接在一起?

Is it possible to chain static together with non-static method in PHP?

这是我的示例代码 Class 用户,但当我使用 public 方法添加静态方法时无法正常工作:

<?php

namespace App\Classic;

class User
{
    public $username;
    public static $upassword;
    public $age;
    public $message;

    public function username($username)
    {
        $this->username = $username;
        echo $this->username."<br>";
        return $this;
    }

    public static function password($upassword)
    {
        self::$upassword = $upassword;
        echo self::$upassword."<br>";
    }

    public function age($age)
    {
        $this->age = $age;
        echo $this->age."<br>";
        return $this;
    }

    public function message($message)
    {
        $this->message = $message;
        echo $this->message."<br>";
        return $this;
    }
}

这是链接方法的副作用:

$user = new User();
$user::password('secret')
     ->username('admin')
     ->age(40)
     ->message('lorem ipsum');

我不知道这样做背后的逻辑是什么,但这个解决方案仍然会有帮助。

Try this code snippet here

<?php

namespace App\Classic;

ini_set('display_errors', 1);

class User
{

    public $username;
    public static $upassword;
    public static $currentObject=null;//added this variable which hold current class object
    public $age;
    public $message;

    public function __construct()//added a constructor which set's current class object in a static variable
    {
        self::$currentObject= $this;
    }
    public function username($username)
    {
        $this->username = $username;
        echo $this->username . "<br>";
        return $this;//added this statment which will return current class object
    }

    public static function password($upassword)
    {
        self::$upassword = $upassword;
        echo self::$upassword . "<br>";
        return self::$currentObject;
    }

    public function age($age)
    {
        $this->age = $age;
        echo $this->age . "<br>";
        return $this;
    }

    public function message($message)
    {
        $this->message = $message;
        echo $this->message . "<br>";
        return $this;
    }

}

$user = new User();
$user::password('secret')
        ->username('admin')
        ->age(40)
        ->message('lorem ipsum');