PHP OOP Performance : Parameter or Instance Variable? [closed]

你说的曾经没有我的故事 提交于 2019-12-24 17:53:29

问题


Im curious about getting an answer for a OOP question but can't find any info so far.

Here goes, writing classes and methods is it faster to pass in parameters for each method or use instance/field variables and $this->x;

Which would be faster at run time?

class ExampleByParameter(){

 function SomeMethod($a,$b){
 echo $a." ".$b;
 return;
 }

}

or

class ExampleByInstance(){

 function __construct($a,$b){
 $this->a=$a;
 $this->b=$b;
 }

 function SomeMehtod(){
 $a=$this->a;
 $b=$this->b;
 echo $a." ".$b;
 return;
 }

}

I would imagine their would be no difference with the examples above but im thinking there might be a significant difference with more complicated code.


回答1:


The performance differece is going to be negligible. You should really be deciding which pattern is best for your class structure.

Does your class depend on $a and $b to operate properly? Put them in the constructor.

Is SomeMethod public? Does it do anything with the supplied variables beyond what it returns? If so, keep them as parameters.

In a large-scale project, you will gain more benefit from accurate class design vs negligible performance improvements.



来源:https://stackoverflow.com/questions/13007658/php-oop-performance-parameter-or-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!