Is there a way to use a function in the declaration of an attribute in PHP? [duplicate]

0

Hello.

You can do something like this:

class Net
{
 public static $ip = getenv("REMOTE_ADDR");
}

Get the return of a function and assign it directly to the property?

Or create a variable outside the class and assign it to a property (without using methods for this):

$ipUser = getenv("REMOTE_ADDR");

class Net
{
public static $ip = $ipUser;
}

It's because it's a class that only has properties, and these properties are being accessed in the static context, so I can not use a constructor or something like that ... or can I?

    
asked by anonymous 03.01.2017 / 17:45

1 answer

4

No, there's no way.

PHP does not allow you to define dynamic values in class attributes literally.

You need to use the constructor for this:

class Net
{
    public $ip;

    public function __construct() {
       $this->ip = getenv("REMOTE_ADDR");
    }
}

$net = new Net;

echo $net->ip;

Or, if it is to use statically, it is necessary to create some method to initialize the attributes:

class Net
{
    public static $ip;

    public static function init() {
       static::$ip = getenv("REMOTE_ADDR");
    }
}


Net::init();

echo Net::$ip;
    
03.01.2017 / 18:22