grottopress / nouveau
此包已被弃用且不再维护。未建议替代包。
通过调用 `::new()` 实例化类,作为 `new` 关键字的替代。
dev-master
2020-02-26 14:54 UTC
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
描述
Nouveau 为您的类添加了一个 new()
静态方法,用于构造类的实例,作为使用 new
关键字的替代。
在 ruby 和 crystal 中,您可以通过以下方式实例化一个类
MyClass.new(*args)
在 rust 中,给一个类型添加一个 构造函数 是一种惯用法
pub struct MyStruct {} impl MyStruct { pub fn new() {} }
...然后这样调用它
MyStruct::new();
Nouveau 将同样的概念带到了 PHP,允许您这样实例化一个类
MyClass::new(..$args);
以上等同于
new MyClass(...$args);
除此之外,这还允许将方法直接链到构造的对象上。
这是
Person::new('John', 'Doe')->fullName();
与
$john = new Person('John', 'Doe'); $john->fullName(); // OR (new Person('John', 'Doe'))->fullName();
用法
通过 composer 安装
composer require grottopress/nouveau
- 将特质导入到您的类中
<?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} :-)"; } }
- 实例化类
$greeter = Vendor\Greeter::new('John'); // Same as `new Vendor\Greeter('John');` echo $greeter->sayHello(); // => Hello, John :-)
请注意,new()
是变长参数,它接受与传递给 __construct()
相同数量的参数。