PHP:类中的静态只读属性

发布于 2024-12-20 02:49:51 字数 392 浏览 0 评论 0原文

我的问题是:我需要重载类中静态变量的标准 get 和 set...但 php 中没有提供此类功能...它在 2008 年被要求但仍未实现...只读也是如此...

我的问题:有没有一种方法可以使静态属性可以从外部读取,但又不能被修改?

echo aaa::$qwe; //<--- echoes value of $qwe
aaa::$qwe = '666'; //<--- throws an error because variable is protected from modification

我不能使用 const 因为有些变量包含数组。

也许有一些解决方法?

是的,我知道我可以像 aaa::Get('qwe') 一样,但这不好......

My problem is: I need to overload standard get and set for static variables in class... but no such functionality provided in php... it was asked in 2008 and still not implemented... Same goes for readonly...

My question: is there a way to make a static property accesible for reading from outside, but protected from modification?

echo aaa::$qwe; //<--- echoes value of $qwe
aaa::$qwe = '666'; //<--- throws an error because variable is protected from modification

I can't use const because some variables contain arrays.

Maybe there are some workarounds?

Yeah, I know I can make it like aaa::Get('qwe') but that's no good...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

千と千尋 2024-12-27 02:49:51

直接回答您的问题:不,您不能将常规属性标记为只读。如果您想设置永远不会改变的基本类型(除了array),您应该使用常量,

const QWE = '666';

这不适用于对象和数组。我看到两个(可以说)“解决方案”

  1. 使用 Getter

    私人$qwe;
    公共函数 getQwe() { return $this->qwe; }
    受保护的函数 setQwe($value) { $this->qwe = $value; }
    

    我不太喜欢它们(“属性定义状态,而不是行为,就像方法一样”)。您总是获得两倍于属性的附加方法,如果您有很多属性,这将极大地破坏您的类。然而,据我所知,这是实现您想要实现的目标的唯一方法。

  2. 相信你的用户;)评论你的属性并说类似“如果你更改此值,可能会出现某些问题,而这都是你自己的错”。

    <前><代码>/**
    * QWE
    *
    * 该属性应被视为“只读”。如果你改变这个值
    * 一些可怕的事情会发生在你身上。
    *
    * @只读
    * @var 字符串
    */
    公共 $qwe = '666';

    这不是很好,但至少你可以说“我告诉过你了”。

Directly answering your question: No, you cannot mark regular properties as readonly. If you want to set primitive types (except array), that will never change, you should use constants

const QWE = '666';

That doesn't work for objects and arrays. I see two (lets say) "solutions"

  1. Use Getter

    private $qwe;
    public function getQwe() { return $this->qwe; }
    protected function setQwe($value) { $this->qwe = $value; }
    

    I don't like them very much ("Properties define the state, not the behavior, like methods do"). You always get twice as much additional methods as properties and if you have many properties, this will extremely blow up your class. However, it's as far as I can see the only way to implement what you want to achieve.

  2. Trust your users ;) Comment your property and say something like "If you change this value, probably something will break and its your very own fault".

    /**
     * QWE
     *
     * This property should be treatened as "readonly". If you change this value
     * something scary will happen to you.
     *
     * @readonly
     * @var string
     */
    public $qwe = '666';
    

    Its not great, but at least you can say "I told you".

心病无药医 2024-12-27 02:49:51

PHP 8.1 中引入了只读属性,但不支持静态只读属性。

来自 RFC

不支持只读静态属性。这是一个技术限制,因为不可能非侵入地实现只读静态属性。结合只读静态属性的可疑用途,目前认为这不值得。

但是,您可以声明一个静态函数来或多或少地获得相同的最终结果。

public static function getType(): string
{
    return 'Duck';
}

Readonly properties were introduced in PHP 8.1, but static readonly properties are not supported.

From the RFC:

Readonly static properties are not supported. This is a technical limitation, in that it is not possible to implement readonly static properties non-intrusively. In conjunction with the questionable usefulness of readonly static properties, this is not considered worthwhile at this time.

However you can declare a static function to more or less get the same end result.

public static function getType(): string
{
    return 'Duck';
}
故事↓在人 2024-12-27 02:49:51

如果该值永远不会改变,您可以使用 const 代替。
否则,就无法满足您的限制(除了通过扩展在 PHP 中挂钩函数调用之外,但即使如此,您也需要将静态变量访问更改为函数调用;否则,您必须修补 PHP)。

当然,您的应用程序所做的是否是良好的设计非常值得怀疑。依赖于改变静态属性或多或少与依赖于全局变量相同。

If the value never changes, you can use const instead.
Otherwise, there's no way that satisfies your restrictions (short of hooking function calls in PHP through an extension, but even then you'd need to change your static variable accesses to function calls; otherwise, you'd have to patch PHP).

Of course, it's highly doubtful that what your application is doing is good design. Relying on changing static properties is more or less the same as relying on global variables.

一抹苦笑 2024-12-27 02:49:51

这更容易一些:

class aaa{
private static $qwe='rty';
public static function qwe() { return self::$qwe; }
}

它不允许更改,并且仍然很容易访问:

aaa::$qwe = 'something'; // fails
echo aaa::qwe(); // success

我知道这并不理想,但您可以将所有内容替换

aaa::$qwe 

aaa::qwe()

This is a bit easier:

class aaa{
private static $qwe='rty';
public static function qwe() { return self::$qwe; }
}

It does not allow changes, and is still easy to access:

aaa::$qwe = 'something'; // fails
echo aaa::qwe(); // success

I know it is not ideal, but you can do a replace all

aaa::$qwe 

with

aaa::qwe()
旧街凉风 2024-12-27 02:49:51

如果 php 提供了 getStatic() 方法,那就太好了,但由于它没有提供,您可以重新利用 __callStatic() 来获取它们,如下所示:

class Foo
{
    private static $readonly_var = 'FOO';
    public static function __callStatic($name, $args) {
        return self::${$name};
    }
}
echo Foo::readonly_var() . PHP_EOL;

只需将变量名称调用为一个函数。它是可扩展的,因为您不需要创建任何特殊的 getter 函数即可使其工作。

It would be nice if php offered a getStatic() method but since it doesn't you can repurpose __callStatic() to fetch them like this:

class Foo
{
    private static $readonly_var = 'FOO';
    public static function __callStatic($name, $args) {
        return self::${$name};
    }
}
echo Foo::readonly_var() . PHP_EOL;

Simply call the variable name as a function. It's scalable since you don't need to create any special getter function for it to work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文