Reputation: 2567
I have defined constant in Laravel as below
class urlConstants
{
const url_01= [ 'id' => 1 , 'text' => 'xxxxxx' ] ;
const url_02= [ 'id' => 2 , 'text' => 'bbbbbb' ] ;
..
const url_99= [ 'id' => 99 , 'text' => 'ccccc' ] ;
}
Now what I wants to do is define new array within urlConstants which include another array like below
class urlConstants
{
const url_01= [ 'id' => 1 , 'text' => 'xxxxxx' ] ;
const url_02= [ 'id' => 2 , 'text' => 'bbbbbb' ] ;
..
const url_99= [ 'id' => 99 , 'text' => 'ccccc' ] ;
// I KNOW I CAN DO SOMETHING LIKE BELOW
const commonArray = [ 1 , 2 , 99 ];
//
}
But I wants to know that is there is any other way to access this variable rather than just typing the integers like below
class urlConstants
{
const url_01= [ 'id' => 1 , 'text' => 'xxxxxx' ] ;
const url_02= [ 'id' => 2 , 'text' => 'bbbbbb' ] ;
..
const url_99= [ 'id' => 99 , 'text' => 'ccccc' ] ;
//
const commonArray = [ url_01['id'] , url_01['id'] , url_01['id'] ];
//
}
Upvotes: 1
Views: 203
Reputation: 13394
I think you don't need to defined constant commonArray
, you can defined a static method,
and call other constants by constant():
public static function commonArray() {
$common_array = array();
$nums = range(1, 99);
foreach($nums as $n) {
$const_name = 'self::url_'. str_pad($n, 2, '0', STR_PAD_LEFT); // this will return self::url_01, self::url_02,...
$common_array []= constant($const_name)['id']; // call the const url_01, url_02...
}
return $common_array;
}
So you can call this commonArray by:
urlConstants::commonArray();
Upvotes: 2