Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading