Reputation: 6379
I was writing unit tests for an entity like this:
class Image
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $path;
/**
* @return string
*/
public function getUrl()
{
return $this->getPath() . $this->getName();
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
}
As you can see the getUrl()
method returns a string formed of path
and name
.
This is the code to test it:
class ImageTest extends \PHPUnit_Framework_TestCase
{
/**
* Tests all get and set methods
*/
public function testImage()
{
$resource = new Image();
$test = array(
'name' => 'testName.jpg',
// Set this without the ending slash (/)
'path' => 'path/to/image',
);
$test['url'] = $test['path'] . $test['name'];
$this->assertEquals($test['name'], $resource->getName());
// Check that, when set, a slash (/) is added at the end of the Path
$this->assertEquals($test['path'] . '/', $resource->getPath());
$this->assertEquals($test['url'], $resource->getUrl());
}
}
As you can see, first has to be created the array
, then it is possibile to set $test['url']
.
At this point the curiosity because I were writing, instead, something like this:
$test = array(
'name' => 'testName.jpg',
'path' => 'path/to/image',
'url' => $test['path'] . '/' . $test['name']
);
But this syntax returns this error:
There was 1 error:
1) Tests\Entity\ImageTest::testImage Undefined variable: test
Maybe is there something like the self
statement for Objects
?
Upvotes: 0
Views: 37
Reputation: 1212
No. The array isn't defined until $test = array(...);
command completes.
$test = array(
'name' => 'testName.jpg',
'path' => 'path/to/image',
);
$test['url'] = $test['path'] . '/' . $test['name'];
It doesn't look as nice as what you're trying to do, but that's the correct way to do it.
Upvotes: 1