Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP如何从类内的其他变量访问变量?_Php_Class_Variables - Fatal编程技术网

PHP如何从类内的其他变量访问变量?

PHP如何从类内的其他变量访问变量?,php,class,variables,Php,Class,Variables,这是我的班级: <?php class myClass { private $a = 1; private $b = array( 'a' => $this->a ); public function getB() { return $this->b; } } $myclass = new myClass(); var_dump($myclass->getB()); 您可以通过构造函数访问

这是我的班级:

<?php
class myClass {
    private $a = 1;
    private $b = array(
        'a' => $this->a
    );

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

您可以通过构造函数访问变量

下面是一些代码:

class myClass {
    private $a;
    private $b;

    public function __construct(){
        $this->a = 1;
        $this->b = array('a'=>$this->a);
    }

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

不允许以这种方式分配变量属性。最好的方法可能是将变量分配给构造函数中的数组。那么像这样,

<?php
class myClass {
    private $a = 1;
    private $b = array();

    public function __construct() {
        $this->b['a'] = $this->a;
    }

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

你不能。只允许在声明之后直接分配常量值。但是不允许使用变量值(您正在尝试的)。这就是构造函数的设计目的。更多信息可以在这里找到:你是对的。最好的解决方案是使用构造函数。
$this
在声明类变量时未定义。调用
\u construct
后,您可以访问
$this
,如果未声明类成员,则不能使用$this__构造似乎是最好的解决方案。但我尝试使用常量而不是普通变量。您可以从php手册中找到一些信息。看一看: