类属性中的PHP函数调用 [英] PHP function call in class property

查看:71
本文介绍了类属性中的PHP函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在PHP中做到这一点?其中Database是单例类,而getInstance()返回一个PDO对象.

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();
    }
}

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

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/zh-CN/language.oop5 .static.php

为什么?!

推荐答案

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

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

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.

重要的是

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

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.

这篇关于类属性中的PHP函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆