【问题标题】:How to make const member-functions in PHP?如何在 PHP 中创建 const 成员函数?
【发布时间】:2018-01-02 14:39:01
【问题描述】:

我正在研究我的书中所说的 C++ 中的“常量成员函数”。即不能改变类的任何属性或调用其他非常量方法的函数。所以,我用 C++ 编写了这段代码。

#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 中这样做。
  • @PaulCrovella 谢谢伙计...但是,你确定吗?没有替代方法吗?
  • 您可以创建做这些事情的方法,但不能创建不能的方法。

标签: php function methods constants php-5.5


【解决方案1】:

在“编译器”级别上的概念并不完全相同,您可以创建不完全相同但也应该“不更改任何类属性或使用其实例”的静态方法。

class Foo {
    public static function bar()
    {
        return 'a static value';
    }
}
//Then to call it:
Foo::bar();

【讨论】:

    【解决方案2】:

    经过一些研究,我在一本书中看到,在 PHP 中创建这样的函数是不可能的,至少不是微不足道的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-04
      • 2016-08-17
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2023-03-14
      • 2013-05-17
      • 2019-05-04
      相关资源
      最近更新 更多