I was just going through a laravel tutrorial online and i saw the following modal coded as below:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notice extends Model {
protected $fillable = [
'provider_id',
'infringing_title',
'infringing_link',
'original_link',
'original_description',
'template',
'content_removed'
];
public static function open(array $attributes) {
return new static($attributes);
}
public function useTemplate($template) {
$this->template = $template;
}
}
What i am interested to know is what exactly is the use of the below method that is defined:
public static function open(array $attributes) {
return new static($attributes);
}
I realize its a static method , but this line return new static($attributes);
particularly confuses me.
I see the method being used in the following way:
$notice = Notice::open($date);
But i still don't quite understand its usage . can somebody explain .
Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method. PHP static methods are most typically used in classes containing static methods only often called utility classes of PHP frameworks like Laravel and CakePHP.
A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.
Example Explained Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).
The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
static method can be used without instantiating the class thus the ::
return new static($attributes);
makes a new model object from that class
which is basically the same as
$notice = new Notice;
$notice->provider_id = $provider_id;
...
all you need to do with the object insatance is call $notice->save()
In this case it is just a syntactic sugar. Someone doesn't seem to like the new
keyword and prefers a more semantic way to instantiate a new notice class, so it reads better.
It also leaves you the doors open for some future logic around instantiating new notice.
Btw. it is model, not modal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With