Jump to content

Syntax with returned array from class method...


cgm225

Recommended Posts

I have a method that returns a two dimensional array, from which I want to set a variable to ONLY the first array contained in the two dimensional array.  Currently, I am doing so successfully like so...

 

        $this->photoData = $this->getSlicedData($this->photoPosition, 1);
        $this->photoData = $this->photoData[0];

 

HOWEVER, I would like to do this all in one line, but am having problems with the syntax...  I want to do something like...

 

        $this->photoData = $this->getSlicedData($this->photoPosition, 1)[0];

 

...but the [ 0 ] I tagged on there is giving me errors...

 

Any ideas?  Thanks again!

For some reason, PHP doesn't allow that syntax (yet.  Hopefully they will soon.  I'd love to see it).  You could always do something like:

 

        $this->photoData = array_shift($this->getSlicedData($this->photoPosition, 1));

$this->photoData = $this->getSlicedData($this->photoPosition, 1)[0];

 

That syntax doesn't make sense. Not to me anyway.

 

It makes as much sense as:

 

<?php
class Test {
protected $other;

public function __construct(Other $other)
{
	$this->other = $other;
}

public function getOther()
{
	return $this->other;
}
}

class Other {
public function test()
{
	echo "Testing";
}
}

$other = new Other();
$test = new Test($other);
$test->getOther()->test();
?>

 

Referring to the last line of that, of course.

No that makes sense, lol.

Because $test->getOther() is an object already.

 

In the OP's example $this->getSlicedData($this->photoPosition, 1) is just calling the function. It isn't an array yet. Which is why this syntax:

$this->getSlicedData($this->photoPosition, 1)[0]

 

Makes no sense.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.