是否可以在PHP中使用非静态方法将静态链接起来?

时间:2017-05-25 09:06:44

标签: php static method-chaining

这是我的示例代码Class User,但是当我使用公共方法添加静态方法时,它不起作用:

    $(document).ready(function(){
          $("#audio").each(function(){
       $(this).attr("controls","");
});
    });

这是链接方法的副作用:

<?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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

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');