【发布时间】:2015-07-07 07:10:19
【问题描述】:
我有一个填充和打印数组的类
<?php
class testArray
{
private $myArr;
public function __construct() {
$myArr = array();
}
public static function PopulateArr() {
$testA = new testArray();
$testA->populateProtectedArr();
return $testA;
}
protected function populateProtectedArr()
{
$this->myArr[0] = 'red';
$this->myArr[1] = 'green';
$this->myArr[2] = 'yellow';
print_r ($this->myArr);
}
public function printArr() {
echo "<br> 2nd Array";
print_r ($this->myArr);
}
}
?>
我从另一个文件实例化这个类,并尝试用不同的函数打印数组。
<?php
require_once "testClass.php";
$u = new testArray();
$u->PopulateArr();
$u->printArr();
?>
我无法在printArr() 函数中打印数组。我想获得对我在 中设置值的数组的引用。
【问题讨论】:
-
您的
populateProtectedArr()需要返回$this->myArr -
公共函数 __construct() { $myArr = array(); } 应该变成: public function __construct() { $this->myArr = array(); }
-
PopulateArr()被定义为static,但您将其称为实例方法 -
@MarkBaker 在这两种情况下你都错了,不需要返回任何东西,也可以从对象调用静态方法
-
@GeorgeGarchagudashvili - 那么也许你会解释发帖人想要做什么,并解释为什么
PopulateArr()被定义为静态?事实上,我已经放弃尝试找出其中的逻辑,直到你告诉我我错了来提醒我