Vahe Vahe - 3 years ago 239
PHP Question

PHP 7 Arrays - Detection of property of an element of a 2D array

I want my PHP IDE (NuSphere PhpEd) to detect a property of my 2D array element ( an object ) whose property is not showing up after I type a right arrow in my IDE.

Is there any way in PHP 7 to auto generate suggestions of a multidimensional array element properties where each element is an object with certain properties?

<?php
class Cell
{
private $color;

public function __construct()
{
$this->color = "red";
}

public function __get($propertyName)
{
if ($propertyName == 'color')
return $this->color;
}

public function __set($propertyName, $value)
{
if ($propertyName == 'color')
$this->color = $value;
}
}

class Matrix implements ArrayAccess
{
private $matrix = array();

public function __construct($maxX, $maxY)
{
$this->matrix = array_fill(1, $maxX, array_fill(1, $maxY, null));
}

public function &offsetGet($name)
{
return $this->matrix[$name];
}

public function offsetSet($name, $value)
{
$this->matrix[$name] = $value;
}

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

public function offsetUnset($name)
{
unset($this->matrix[$name]);
}
}


$matrix = new Matrix(3,3);
for ($xIdx = 1; $xIdx <= 3; $xIdx++)
for ($yIdx = 1; $yIdx <= 3; $yIdx++)
$matrix[$xIdx][$yIdx] = new Cell();

$matrix[2][2]->color = "green";
echo $matrix[2][2]->color;
?>

Answer Source

If you're happy to use phpdoc annotations, you can use the Type[][] annotation to declare a variable as being a 2D array of Type. In the case of a class property that looks like:

/** @var Cell[][] */
private $matrix = [];

Or for the return value of a class method:

/**
 * @return Cell[][]
 */
public function getMatrix() {
    return $this->matrix;
}

In the case of PHPStorm, that provides this:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download