Error using a function inside array in PHP

3

I'm using laravel 5.2 and in my class IndexController I'm trying to create an array with the function date('Y') like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class IndexController extends Controller
{   
    var $arr = array('ano' => date('Y'),
                     'titulo' => 'Titulo do projeto');

    public function Index()
    {        
        //passo o array para a view.       
        return view('welcome')->with($arr);
    }
}

but I'm getting the following error:

  

syntax error, unexpected '(', expecting ')'

Does anyone know why? Am I doing something wrong?

    
asked by anonymous 08.05.2016 / 21:19

1 answer

6
The problem is that you are trying to create an array with a non-literal value It would probably be better to use a class member instead of trying to create a function-dependent value within array .

As you have not explained exactly how you will use $arr , I do not know if this is, but here is a small example of how to initialize a data in the function constructor:

class MinhaClasse
{   
    public $arr = array();

    function __construct() {
        $this->arr['ano'] = date('Y');
    }

    public function getAno()
    {              
        return $this->arr['ano'];
    }
}

However, this generates a side effect, which can be seen in IDEONE:

  

link

Because the value can change with each instantiation of the object, this is probably not what you want. It would be nice to specify at what point in time you are going to need the value, as it may be the case of static , or pass the value in the constructor. If you are going to use static , you need a if( isset( ) ) in the constructor, if you do not want to change the value of all instances and keep the first instance only (I think it leaves the code a bit "unsafe" you have a deep grasp of what you are doing.)

The var , in PHP 5 it is synonymous with public , but gives a warning (or error, if you work with STRICT mode).

Maybe the solution is not to put the year in the class creation, but rather to define it in PHP when using it:

class MinhaClasse
{   
    public $arr = array();

    public function setAno( $ano ) {
        $this->arr['ano'] = $ano;
    }

    public function getAno()
    {              
        return $this->arr['ano'];
    }
}

And time to use:

$objeto = new MinhaClasse();
$objeto->setAno( date( 'Y' ) );
// agora vc usa o objeto onde precisar
    
08.05.2016 / 22:07