静态构造函数的最佳实践 [英] Best practices for static constructors

查看:100
本文介绍了静态构造函数的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一行代码中创建一个类的实例并调用该实例的方法。



PHP不允许调用方法在常规构造函数上:

  new Foo() - > set_sth //输出错误。 

所以我使用,如果我可以调用它,一个静态构造函数:

  Foo :: construct() - > set_sth(); 

这是我的问题:



静态构造函数,如果这被认为是一个好的做法,如果是,你将如何建议命名这些静态构造函数的方法?



我一直犹豫以下选项: / p>

  Foo :: construct(); 
Foo :: create();
Foo :: factory()
Foo :: Foo();
constructor :: Foo();


解决方案

任何方法的命名应该是意图显示名称。我不能告诉什么'Foo ::工厂'。尝试构建更高级别的语言:

  User :: with100StartingPoints(); 

这将是相同的:

  $ user = new User(); 
$ user-> setPointsTo(100);

您也可以轻松测试User :: with100StartingPoints()是否等于此。

I want to create an instance of a class and call a method on that instance, in a single line of code.

PHP won't allow calling a method on a regular constructor:

new Foo()->set_sth(); // Outputs an error.

So I'm using, if I can call it that, a static constructor:

Foo::construct()->set_sth();

Here's my question:

Is using static constructors like that considered a good practice and if yes, how would you recommend naming the methods for these static constructors?

I've been hesitating over the following options:

Foo::construct();
Foo::create();
Foo::factory()
Foo::Foo();
constructor::Foo();

解决方案

The naming of any method should be with intention revealing names. I can't tell what 'Foo::factory' does. Try to build to a higher level language:

User::with100StartingPoints();

This would be the same as:

$user = new User();
$user->setPointsTo(100);

You could also easily test whether User::with100StartingPoints() is equal to this.

这篇关于静态构造函数的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆