php中类错误中的数组引用
发布时间:2020-12-13 16:57:15 所属栏目:PHP教程 来源:网络整理
导读:我有这个类填充和打印一个数组 ?phpclass testArray{ private $myArr; public function __construct() { $myArr = array(); } public static function PopulateArr() { $testA = new testArray(); $testA-populateProtectedArr(); return $testA; } protecte
我有这个类填充和打印一个数组
<?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()函数中打印数组.我想引用我设置值的数组. 解决方法
你错过了一件事,你必须分配$u-> PopulateArr()的结果;再次使用$u,否则您将无法从该方法调用中获取您创建的对象,因此:
$u = new testArray(); $u = $u->PopulateArr(); // this will work $u->printArr(); 这也可以这样做: $u = testArray::PopulateArr(); $u->printArr(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |