类属性中的 PHP 函数调用

2021-12-26 00:00:00 static singleton php pdo

为什么我不能在 PHP 中执行此操作?其中 Database 是一个单例类,getInstance() 返回一个 PDO 对象.

query("SELECT * FROM blah");返回 $stmt->fetch();}}

<块引用>

与任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许使用表达式.因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象.

http://php.net/manual/en/language.oop5.static.php

为什么?!

解决方案

http://php.net/language.oop5.properties

<块引用>

类成员变量称为属性".您可能还会看到使用其他术语(例如属性"或字段")来引用它们,但出于此引用的目的,我们将使用属性".它们是通过使用关键字 public、protected 或 private 之一来定义的,后跟一个普通的变量声明.此声明可能包含一个初始化,但此初始化必须是一个常量值——也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估.强>

最重要的是

<块引用>

也就是说,它必须能够在编译时被评估

表达式是在运行时求值的,所以不能使用表达式来初始化属性:它们根本就不能求值.

Why can't I do this in PHP? Where Database is a singleton class and getInstance() returns a PDO object.

<?php

class AnExample
{
    protected static $db = Database::getInstance();

    public static function doSomeQuery()
    {
        $stmt = static::$db->query("SELECT * FROM blah");
        return $stmt->fetch();
    }
}

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

http://php.net/manual/en/language.oop5.static.php

Why?!

解决方案

http://php.net/language.oop5.properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

The important part is

that is, it must be able to be evaluated at compile time

Expressions were evaluated at runtime, so it isn't possible to use expression to initialize properties: They are simply not evaluatable yet.

相关文章