【问题标题】:Array reference in a class error in phpphp中类错误中的数组引用
【发布时间】: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-&gt;myArr
  • 公共函数 __construct() { $myArr = array(); } 应该变成: public function __construct() { $this->myArr = array(); }
  • PopulateArr() 被定义为 static,但您将其称为实例方法
  • @MarkBaker 在这两种情况下你都错了,不需要返回任何东西,也可以从对象调用静态方法
  • @GeorgeGarchagudashvili - 那么也许你会解释发帖人想要做什么,并解释为什么PopulateArr() 被定义为静态?事实上,我已经放弃尝试找出其中的逻辑,直到你告诉我我错了来提醒我

标签: php arrays class object


【解决方案1】:

你只是错过了一件事,你必须再次将$u-&gt;PopulateArr();的结果分配给$u,否则你将无法获得你从该方法调用中创建的对象,所以:

$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();

这也可以这样做:

$u = testArray::PopulateArr();
$u->printArr();

【讨论】:

    【解决方案2】:

    您的 $u 对象似乎从未填充私有数组。

    相反,您创建一个新对象 $testA 并填充其数组。

    【讨论】:

      【解决方案3】:

      这可能有助于您了解方式

      class testArray
      {
          private $myArr;
      
          public function __construct() { 
              $this->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';
              return $this->myArr;
          }
          public function printArr() {
              echo "<br> 2nd Array";
              return $this->PopulateArr();
          }
      }
      

      另一个.php

      require_once "testClass.php";
      $u = new testArray();
      print_r($u->PopulateArr());
      print_r($u->printArr());
      

      这里我们访问的是protected function PopulateArr 的值,而不是在函数中打印我只是将它替换为return 并将其打印到另一个文件上,在printArr 函数中调用PopulateArr 函数就可以了

      【讨论】:

        猜你喜欢
        • 2017-05-04
        • 1970-01-01
        • 1970-01-01
        • 2015-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        • 2013-03-12
        相关资源
        最近更新 更多