【问题标题】:How to create objects in PHP [duplicate]如何在 PHP 中创建对象 [重复]
【发布时间】:2013-02-08 16:29:50
【问题描述】:

我很难理解如何在我的脚本中创建对象......我收到此错误:

PHP Fatal error:  Call to undefined function Object()

我的代码是这样的:

$block = Object();  // error here
$row['x'] = 5;
$row['y'] = 7;
$row['widthx'] = 3;
$row['widthy'] = 3;

for($i = $row['x']; $i < ($row['x'] +  $row['widthx']); $i++){

    if(!is_object($block[$i])){
        $block[$i] = Object();
    }


}

谁能解释我做错了什么?

【问题讨论】:

标签: php


【解决方案1】:

在最简单的形式中,对象就是类。

class coOrds {

    // create a store for coordinates
    private $xy;

    function __contruct() {

        // it's still an array in the end
        $this->xy = array();

    }

    function checkXY($x, $y) {

        // check if xy exists
        return isset($this->xy[$x][$y]);

    }

    function saveXY($x, $y) {

        // check if XY exists
        if ($this->checkXY) {

            // it already exists
            return false;

        } else {

            // save it
            if (!isset($this->xy[$x])) {

                // create x if it doesn't already exist
                $this->xy[$x] = array();

            }

            // create y
            $this->xy[$x][$y] = '';

            // return
            return true;

        }

    }

}

$coords = new coOrds();

$coords->saveXY(4, 5); // true
$coords->saveXY(5, 5); // true
$coords->saveXY(4, 5); // false, already exists    

从这里开始阅读它们:http://www.php.net/manual/en/language.oop5.basic.php

【讨论】:

  • 嗯,我没有看到如何从循环中创建对象列表 =/
  • 我认为您需要问自己“我为什么要尝试从循环中创建对象?”。如果您不了解对象,我不明白您为什么要尝试创建它们或它们将用于什么目的。
  • 嗯,我想遍历它们,因为它们拥有 X 和 Y 坐标……如果我使用循环对象而不是数组,它将节省循环时间。因为我可以检查 object[$x] 是否存在 - 如果不存在,则无需继续检查.. 如果它是一个数组,我必须检查它们以 100% 确保值不存在
  • 你解释的是一个数组。您想检查 array[$x] 是否存在。我仍然不明白你为什么要创建一堆对象,而这些对象除了从数组中得到的东西之外什么都没有。如果您正在检查键,它只会在数组中存在一次,因为您不能复制键。
  • 因为创建这样的数组:$myarray[$x][$y]; 来存储坐标通常会出现很多Undefined offset 警告,所以我的替代选择是创建对象。
【解决方案2】:

您需要定义类并将它们实例化为对象:

    class Object {
        private $name;

        __construct($name){
            $this->name=$name
        }

        public function setName($name)
        {
            $this->name = $name;

            return $this;
        }

        public function getName()
        {
            return $this->name;
        }
    }

    $block = $new Object($name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2014-04-28
    • 2015-09-11
    • 1970-01-01
    • 2013-12-21
    • 2015-02-06
    相关资源
    最近更新 更多