在php中其他private var的声明中使用private var [英] Use private var in declaration of other private var in php

查看:447
本文介绍了在php中其他private var的声明中使用private var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用私有变量声明另一个私有变量?我的代码如下:

Is there a way to use a private variable to declare an other private variable? My Code looks like this:

class MyClass{
    private $myVar = "someText";
    private $myOtherVar = "something" . $this->myVar . "else";
}

但这以PHP Fatal error: Constant expression contains invalid operations

$this->一起尝试过

有没有办法在php中做到这一点?

Is there a way to do this in php?

推荐答案

属性的默认值在编译时不能基于其他属性.但是,有两种选择.

Default values for properties can't be based on other properties at compile-time. However, there are two alternatives.

常量可以使用默认值:

class MyClass {
    const MY_CONST = "someText";
    private $myVar = self::MY_CONST;
    private $myOtherVar = "something" . self::MY_CONST . "else";
}

从PHP 7.1开始,这样的常数本身可以是私有的(private const).

As of PHP 7.1, such a constant could itself be private (private const).

可以声明没有默认值的属性,并在类的构造函数中为其赋值:

Properties can be declared with no default value, and assigned a value in the class's constructor:

class MyClass {
    private $myVar = "someText";
    private $myOtherVar;

    public function __construct() {
        $this->myOtherVar = "something" . $this->myVar . "else";
    }
}

这篇关于在php中其他private var的声明中使用private var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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