Result of a function in an array

Asked

Viewed 161 times

2

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

I tried to use the function date('Y') directly in the attribution of the property, however as 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 class constructor method:

<?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 via the constructor?

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

  • 1

    As far as I know, it is not possible to define a property with function value.

2 answers

1


You could use a GETTER... is ugly and dirty, but take 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" } 
  • 1

    I just implement a static getter in this case, inserting the position with dynamic value in the static variable.

1

You can’t really put methods or functions in properties in PHP, according to the documentation itself php.net

As an alternative I thought to declare these guys with constants using the defines

<?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 );

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.