如何在PhP中创建const成员函数?
问题描述:
我正在研究我的书在C++中被称为“常量成员函数”。也就是说,不能改变类的任何属性或调用其他非常量方法的函数。所以,我在C++中做了这段代码。如何在PhP中创建const成员函数?
#include <iostream>
#include <string>
using namespace std;
class Foo
{
string outra_coisa;
public:
void printa_algo(string algo) const;
};
int main()
{
Foo tolo;
string alguma_coisa = "coisa_alguma";
tolo.printa_algo(alguma_coisa);
return 0;
}
void Foo::printa_algo(string algo) const
{
cout << algo;
}
是否有可能做同样的在PHP?
答
经过一番研究,我在书中看到,在PhP中创建这样的功能是不可能的,至少不是微不足道的。
答
它在“编译器”级别上的概念不完全相同,您可以创建不完全相同的静态方法,但也应该“不更改任何类属性或使用其实例”。
class Foo {
public static function bar()
{
return 'a static value';
}
}
//Then to call it:
Foo::bar();
不,你不能在PHP中这样做。 –
@PaulCrovella谢谢你......但是,你确定吗?没有其他方法吗? – BrunoVdutra
你可以创建*不*做这些事情的方法,但不能*做不到*的方法。 –