PHP 非客户端编码器类执行
简单的理论问题
当构建一个不会被任何其他客户端编码人员使用的类时,最好的执行方法是什么?考虑以下事项:
class Test
{
public function __construct()
{
$this->foo();
$this->bar();
}
public function foo(){ //do something }
public function bar(){ //do something }
}
$test = new Test;
由于我确切地知道我想要这个类做什么以及它应该完成的顺序,所以我只需在构造过程中调用这些函数即可。然而,同样可以通过这样做来完成:
class Test
{
public function __construct(){}
public function foo(){ //do something }
public function bar(){ //do something }
}
$test = new Test();
$test->foo();
$test->bar();
以一种方式或另一种方式这样做有什么优点?无论是性能、调试等。
编辑
这是一个通用问题。希望了解有关在类中执行方法的这两种方式的所有可能性和担忧。
Simply question of theory
When building a class that is not going to be used by any other client-coders, what is the best method of execution? Consider the following:
class Test
{
public function __construct()
{
$this->foo();
$this->bar();
}
public function foo(){ //do something }
public function bar(){ //do something }
}
$test = new Test;
As I know exactly what I want this class to do, and the order it should be done in, I simply call the functions during construction. However The same can be done by doing:
class Test
{
public function __construct(){}
public function foo(){ //do something }
public function bar(){ //do something }
}
$test = new Test();
$test->foo();
$test->bar();
What are the advantages to doing it one way or the other? Be it performance, debugging, etc.
Edit
This is a general purpose question. Looking to hear all possibilities and concerns regarding these two ways of executing methods within a class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种方法中,您可以将这些函数设为私有,并仅在对象本身内使用它们。
如果将函数设置为
protected
而不是private
,则从此类继承的任何类都将能够使用这些函数(同时仍然不允许调用这些函数)在外部)使用第二个选项时,任何对象都可以在类定义之外调用这些函数,并且根据您的代码,您可能不希望这样做。
In the 1st way you can make those functions
private
and use them only within the object itself.If you make the functions
protected
instead ofprivate
, any class that inherits from this class would be able to to use the functions (while still not allowing for the functions to be called on the outside)With your second option, any object can call those functions outside the class definition, and depending on your code, you might not want that.
详细说明尼尔的答案:如果可以的话,将函数设为私有。这样,如果您以后想要更改它们,您就知道它们仅在其类中使用。
因此,回答您的问题:第一个答案是首选,因为它使您的代码更易于维护。就性能而言,没有区别。
To elaborate on Neal's answer: If you can, make the functions private. That way, if you want to change them later, you know they are only used within their class.
So, to answer you question: The first answer is preferred because is makes your code easier to maintain. Performance wise, there is no difference.