简体   繁体   中英

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

Here is my sample code Class User but not working when I added the static method with the public methods:

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

and this is the side effect of chaining method:

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

I dont know what is the logic behind doing this, but still this solution will be helpful.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM