A class that implements ArrayAccess throws Fatal Error if the first one is not specified

I have the following file:

<?php

$inc = new includer;

?>

<!-- ... snip lots of HTML ... -->

<?php

class includer {

    protected $obj;

    public function __construct() {
        $this->obj = new obj;
    }

}

// obj taken from PHP ArrayAccess page as example, contents not important
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

When a class instance includeris at the bottom of the file (with class definitions at the top of the file), everything works fine. With creating a class at the top of the file as shown, I get the following error:

Fatal error: Uncaught Error: Class 'obj' not found in \test\classes.php on line 16

If I remove a part implements ArrayAccessfrom the class obj, everything works fine, regardless of where the includerinstance is created.

The file is a one-page PHP / HTML / JS file with all my PHP classes and function definitions below. Therefore, I would really like these classes not to be on top, just because of the part ArrayAccess. I also don't need a lecture on spaghetti codes, etc. It was a conscious decision to write like that.

parens ($inc = new includer; vs $inc = new includer();), .

(\ArrayAccess vs ArrayAccess), .

, PHP - , , ? ( ArrayAccess) .

+4
1

, ArrayAccess.

PHP , ( ) :

, . , . ( ).

, , , .

, , , , , , .

+1

Source: https://habr.com/ru/post/1691666/


All Articles