既不是方法也不是静态的类函数


PHP Class functions that are neither methods nor static

我想在我的类中使用一个函数来执行一个简单的任务,例如:

function hello($name) { return 'hello '.$name; }

。不一定是静态的(尽管我认为它可能是),但与对象无关(不需要引用$this)。

是否使用静态函数?ie .

static function hello($name){return 'hello '.$name;}

,用$string = ClassName::hello('Alex');

命名

还是有更好的方法?

谢谢!

不需要调用object的实例并且不需要object的实例就可以执行的类方法应该声明为static。

静态方法没有$this,应该像ClassName::methodName()那样调用。

静态方法可以访问类的静态成员变量

静态函数就是静态函数。
如果它是无状态的,那么使用static。

你也可以在一个类*Utils中封装一组相似的函数。这些函数就像helpers

class StringUtils{
function splitBy($delimeter,$val){....}
}
than you call it StringUtils::splitBy(..)

表示如果它与对象无关,则将其分开。

您可以随身携带utils文件夹到每个项目并不断重复使用....

  1. 这个类中的这个函数是什么?如果它不属于它-就移到其他地方
  2. …如果属于,则问题有可能在不创建对象的情况下调用它

如果没有对$this的引用(或将来可能对$this的引用),则将其设置为静态

我这样说是因为有时我用:

static function hello( $name ) { return 'hello '.$name; }

,经过几个月的开发和扩展程序后,我觉得有必要引用$this,如:

function hello( $name ) { return $this->helloInLanguage[ $this->language ].' '.$name; };