Can I use a function in the declaration of an attribute in PHP?

Asked

Viewed 48 times

0

Hello.

You can do something like:

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

Take the return of a function and assign directly in 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;
}

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

  • 2

    Net::ip = getenv("REMOTE_ADDR"); has any problem using or does not meet your requirement? related

  • In this case it was just one example. : x my real situation is a class settings that has an attribute 'approot', which I wanted to receive a different path depending on the environment (local or web), if ip is 127.0.0.1 gets path x, if it’s another, path y. then I would create a function to verify ip.

  • if you have no way, I will create a method for it. But I wanted to know if there is how, for purposes of experience.

  • 1

    Looks like it’s duplicated: Instantiation of objects in PHP

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 using statically, you need 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;

Browser other questions tagged

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