简体   繁体   English

你能在 PHP 的 function 中设置一个常量 class 属性吗?

[英]Can you set a constant class property inside function in PHP?

Sorry for the weird title wording.对不起,奇怪的标题措辞。

I want a class to have a property that can be viewed but not changed, and I want to set it inside a function.我希望 class 具有可以查看但不能更改的属性,并且我想将其设置在 function 中。

Like this:像这样:

class Foo {
    public int $bar;

    public function __construct(int $input) {
        if ($input < 4) {
            $this->bar = $input;
        }
    }
}

$foo = new Foo(2);
echo $foo->bar; // Returns 2
$foo->bar = 1   // Gives error

Yes, this is possible and a very common practice:是的,这是可能的,也是一种非常普遍的做法:

class Foo
{
    private $bar;

    public function getBar()
    {
        return $this->bar;
    }

    public function __construct() {
        // set $bar according to some logic
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM