Result of a function in an array

2

I would like to insert the current year into an array property of a class.

I tried to use the date('Y') function directly in the property assignment, but it did not work.

<?php

class MyClass {

    public $myArray = [
        'teste' => 'valor',
        'ano' => date('Y')
    ];

    // código
}

var_dump( (new MyClass())->myArray );

Temporarily, I solved this problem by initializing this value in the constructor method of the class:

<?php

class MyClass {

    public $myArray = [
        'teste' => 'valor',
        'ano' => ''
    ];

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

    // código
}

var_dump( (new MyClass())->myArray );

Is there any way to assign the result of a function to a property, without resorting to an assignment through the constructor?

I would not like to use the constructor because I plan to leave this variable as static

    
asked by anonymous 13.08.2014 / 22:19

2 answers

1

You could use a GETTER ... it's ugly and dirty, but take it as a didactic model. If you can give some more information about class behavior it is easier to give a real example.

class MyClass
{
    public static $myArray = array( 'teste' => 'valor' , 'ano' => null );

    public function __get( $name )
    {
        return static::$myArray;
    }

    public function __construct()
    {
        static::$myArray['ano'] = date('Y');
    }
}

var_dump( (new MyClass())-> myArray );

Output:

array(2) { ["teste"]=> string(5) "valor" ["ano"]=> string(4) "2014" } 
    
13.08.2014 / 22:40
1

You do not really need methods or functions in properties in PHP, according to the php.net documentation

Alternatively, I thought of declaring these types with constants using define

<?php

date_default_timezone_set("America/Sao_Paulo");

define("DATA",date("Y"));

class MyClass {
  // talvez
  //const DATA = DATA;

    public $myArray = DATA;

    // código
}

var_dump( (new MyClass())->myArray );

?>
    
13.08.2014 / 22:55