grottopress / nouveau
Instantiate a class by calling `::new()`, as an alternative to the `new` keyword.
Requires
- php: >=7.0
Requires (Dev)
- codeception/codeception: ^2.3
This package is auto-updated.
Last update: 2020-03-02 18:35:32 UTC
README
Description
Nouveau adds a new()
static method to your class for constructing an instance of the class, as an alternative to using the new
keyword.
In ruby and crystal, you instantiate a class by doing:
MyClass.new(*args)
In rust, it is idiomatic to add a constructor to a type:
pub struct MyStruct {} impl MyStruct { pub fn new() {} }
...and call it thus:
MyStruct::new();
Nouveau brings the same concept to PHP, allowing to intantiate a class thus:
MyClass::new(..$args);
The above is equivalent to:
new MyClass(...$args);
Among other things, this allows chaining a method immediately unto the constructed object.
This:
Person::new('John', 'Doe')->fullName();
Versus:
$john = new Person('John', 'Doe'); $john->fullName(); // OR (new Person('John', 'Doe'))->fullName();
Usage
Install via composer:
composer require grottopress/nouveau
- Import trait into your class:
<?php declare (strict_types = 1); namespace Vendor; use GrottoPress\Nouveau\NewTrait; class Greeter { /** * Import trait */ use NewTrait; private $name; public function __construct(string $name) { $this->name = $name; } public function sayHello(): string { return "Hello, {$this->name} :-)"; } }
- Instantiate class
$greeter = Vendor\Greeter::new('John'); // Same as `new Vendor\Greeter('John');` echo $greeter->sayHello(); // => Hello, John :-)
Note that new()
is variadic, and takes as many arguments as you pass to __construct()
.