php - How to set public variable dynamically when a class instance is created

720

When I initialize a new class instance I want to set a public variable based on the current url.

How do I go about setting the public variable dynamically when the class instance is created so it is available without having to call a function.

 class CONFIGURATOR{
    static public $ACTIVE = true;
    public $CURRENT_URL="<current_url here>"
  }
870

Answer

Solution:

Use the constructor :

class CONFIGURATOR{
   static public $ACTIVE = true;
   public $CURRENT_URL="<current_url here>"

   public function __construct($url)
   {
       $this->CURRENT_URL = $url;
   }
}

You can call your object like this :

$configurator = new CONFIGURATOR($your_url);
482

Answer

Solution:

Use constructor , it may be solve your problem

class CONFIGURATOR{
    static public $ACTIVE = true;
    public $CURRENT_URL="";

    function __construct()
    {
        $this->$CURRENT_URL="<current_url here>";
    }
  }

Thank You

People are also looking for solutions to the problem: php - fgets(STDIN) automatic line break?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.