How to call to an static class and method with PHP

This is my first post here 🙂

I have a noob question about PHP.

How can I create a class to be called in this way?

Carbon::parse( $date )->addDay();

I was creating something like that and do not works:

class DateClass
{
      
    public static $date;

    public static function create( $date ){   
        self::$date = $date;
    }
    
    public static function toHuman(){   
       // Here I want to transform date and returned
    }


}

And call it like:

DateClass::create( $date )->toHuman();

Anybody can help me please???

Thaaanks a lotin advance!
I’ll appreciate a lot your comments <3

>Solution :

I think that code will explain this best:

class DateClass
{
    public $date;

    public static function create( $date ){
        $object = new self();
        $object->date = $date;

        return $object;
    }

    public function toHuman(){   
       // Do your transformations using $this->date object
    }
}

If you want to use static methods, use them just for creating object – there is no requirement that class should have only static or non-static members. Initialise self object (equivalent to new DateClass()), set what you want – using constructor of property access – and return result. In this way you can use your class in "chain", like you want: DateClass::create( $date )->toHuman();

Leave a Reply