【问题标题】:PHP Class properties are empty when initialized in constructorPHP 类属性在构造函数中初始化时为空
【发布时间】:2019-07-31 03:25:11
【问题描述】:

我正在编写一个非常简单的 php 类来做一些测试,但是我在构造函数中初始化的变量仍然是空的:

class Zip {

private $root;


public function _construct() {
    $this->root=dirname(__DIR__);
}

public function print(){ echo $this->root;};

}

当我打印变量时,ir 什么都不返回,并且在检查后它只是空值。 为什么这不起作用?

【问题讨论】:

  • 打印功能后不需要的分号? public function print(){ echo $this->root;}; 不确定这是否是导致问题的原因。还可以尝试从构造函数中回显某些内容,以查看它是否真正运行。
  • 可能是因为你漏掉了一个下划线?这是__construct()

标签: php class properties


【解决方案1】:

简单地尝试一下:-

class Zip {

    private $root;


    public function __construct() {
        $this->root = dirname(__DIR__);
    }

    public function print()
    { 
      echo $this->root;
    }
}

之后:-

$object = new Zip();
echo $object->print();

构造函数应该有__,而你缺少类结束},删除最后一个分号,你不需要它。

【讨论】:

  • 缺少下划线。
猜你喜欢
  • 2015-09-11
  • 2021-11-16
  • 2021-03-07
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多