【问题标题】:How do I properly construct an array within a class in PHP?如何在 PHP 的类中正确构造数组?
【发布时间】:2017-06-16 19:10:30
【问题描述】:

目前我正在用 PHP 编写一个简单的 OOP 脚本,它需要比较数组的 ID 和 DATE 并按正确的顺序对它们进行排序。

我想知道为什么我的第一个类中的构造函数没有正确传递 $elements 数组。

我得到的错误:

注意:未定义变量:第 58 行 /Applications/XAMPP/xamppfiles/htdocs/strategy-pattern-.php 中的元素

可捕获的致命错误:传递给 ObjectCollection::__construct() 的参数 1 必须是数组类型,给定 null,在第 58 行的 ... 中调用并在第 12 行的 ... 中定义

代码:

<?php

class ObjectCollection
{

var $elements = array(
 array('id' => 2, 'date' => '2017-01-01',),
 array('id' => 1, 'date' => '2017-02-01')); 

var $comparator;

    function __construct(array $elements)
    {
        $this->elements = $elements;
    }

    function sort()
    {
        if (!$this->comparator) {
            throw new \LogicException('Comparator is not set');
        }

        uasort($this->elements, [$this->comparator, 'compare']);

        return $this->elements;
    }

    function setComparator(ComparatorInterface $comparator)
    {
        $this->comparator = $comparator;
    }
}

interface ComparatorInterface
{
    function compare($a, $b);
}

class DateComparator implements ComparatorInterface
{
    function compare($a, $b)
    {
        $aDate = new \DateTime($a['date']);
        $bDate = new \DateTime($b['date']);

        return $aDate <> $bDate;
    }
}

class IdComparator implements ComparatorInterface
{
    function compare($a, $b)
    {
        return $a['id'] <> $b['id'];
    }
}

 $collection = new ObjectCollection($elements);
 $collection->setComparator(new IdComparator());
 $collection->sort(); 
 echo "Sorted by ID:\n <br>";
 print_r($collection->elements);
 $collection->setComparator(new DateComparator());
 $collection->sort();
 echo "<br>Sorted by date:\n <br>";
 print_r($collection->elements); 

?>

我知道某处可能只是一个新手错误,但我真的很好奇我做错了什么哈哈。

提前致谢! :)

【问题讨论】:

  • 好吧,var 已经有一段时间没有使用属性定义了。你用的是什么手册? PHP4

标签: php arrays class


【解决方案1】:

在你的脚本底部有:

$collection = new ObjectCollection($elements);

但是,$elements 变量未定义。这就是您收到错误的原因。

具体错误与您在类构造函数中使用type declaration 要求传递“数组”这一事实有关。在 php 中添加类型声明之前,php 运行时引擎并不关心你传递了什么变量,只要你传递的变量数量等于所需参数的数量给一个函数或方法。

正如另一个答案中所指出的那样,我们中的许多人都假设您将 --

var $elements = array(
  array('id' => 2, 'date' => '2017-01-01',),
  array('id' => 1, 'date' => '2017-02-01')); 

从来没有打算在课堂上。话虽如此,这样做会创建并初始化 $elements 类变量,这是一种在 OOP 中有很多用途的有效技术。但是,使用的语法已经过时,如果您确实想在对象创建时将类变量初始化为设定值,您应该使用包含 variable visibility 关键字的语法,例如:

protected $elements = array(
  array('id' => 2, 'date' => '2017-01-01',),
  array('id' => 1, 'date' => '2017-02-01')); 

总之,您的问题的答案是您应该将 $collection 定义为脚本底部的数组,或者在创建 ObjectCollection 对象时传入一个数组.

$collection = new ObjectCollection(array(
     array('id' => 2, 'date' => '2017-01-01'),
     array('id' => 1, 'date' => '2017-02-01'));

【讨论】:

  • 很高兴为您提供帮助。由于您似乎在做一些学习练习,因此将多个类放在同一个脚本中是可以理解的,但是在专业/现实世界的 php 中,您希望始终将您的类放在单独的脚本中,并相应地命名。请参阅此标准”php-fig.org/psr/psr-1 这样做非常重要,因为 php 具有命名空间和组件库,以及执行依赖管理并生成要在项目中使用的自动加载器的 composer 工具。
  • @gview 一定会检查链接,感谢您的建议!
【解决方案2】:
class ObjectCollection
{
    // define as property
    private $elements;

    private $comparator;

    function __construct(array $elements)
    {
        $this->elements = $elements;
    }

    function sort()
    {
        if (!$this->comparator) {
            throw new \LogicException('Comparator is not set');
        }

        uasort($this->elements, [$this->comparator, 'compare']);

        return $this->elements;
    }

    function setComparator(ComparatorInterface $comparator)
    {
        $this->comparator = $comparator;
    }
}


... 

// you need to define $elements to pass 
$elements = array(
 array('id' => 2, 'date' => '2017-01-01',),
 array('id' => 1, 'date' => '2017-02-01')); 

// them to the constructor
$collection = new ObjectCollection($elements);



// the way you did it, your $elements definition was in class scope so you got the error they are "NULL" / Not defined

【讨论】:

  • 是的,但是您必须丢失 var 关键字。
  • 解释为什么这会回答这个问题会有所帮助。仅代码的答案并没有真正的启发性。
  • 一个好的答案总是会解释做了什么以及为什么这样做,不仅是为了 OP,而且对于可能会发现这个的 SO 的未来访问者问题并阅读您的答案。
【解决方案3】:

您已经在类内部而不是外部声明了 elements 变量

$elements = array(
 array('id' => 2, 'date' => '2017-01-01',),
 array('id' => 1, 'date' => '2017-02-01')); 

class ObjectCollection
{

【讨论】:

  • @trincot PHP 中也不需要var
猜你喜欢
  • 2015-03-16
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 2012-09-30
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多