简体   繁体   中英

How to declare a php variable to be constant

I have some closures that I have bound to some variables.

eg

$x = function() { echo "hi there"; };

I want to make sure that $x never gets inadvertently switched to some other value. Any idea how to do this?

I can't use constants as they only resolve to scalar values.

What's the purpose of this code?

I mean, functions are constants by themselves, as they cannot be re-declared . Why not doing this instead then?

function x() { echo "hi there"; };

If you're working in a closure, you can always use a namespace , so your function won't meet with a colliding one outside of the closure.

I Don't think you can achieve that as:

  • Variables are meant to change their value
  • Constants can't hold a function

But I came with a workaround, is the only thing I came up with, dunno if it will be ok for you: Using Classes And it's __destruct() magic method

Class Hulk {
    function __construct(){
        echo "Hulk is born!<br>";
    }

    function __destruct(){
        throw new Exception('Someone is trying to destroy Hulk, not knowing that he is indestructible!!!');
    }
}

$x = new Hulk();
$x = "hello";

When you try to assign "hello" to X it will throw an exception:

 Fatal error: Uncaught exception 'Exception' with message 'Someone is trying to destroy Hulk, not knowing that he is indestructible!!!' in /Applications/MAMP/htdocs/test.php:38 Stack trace: #0 /Applications/MAMP/htdocs/test.php(44): Hulk->__destruct() #1 {main} thrown in /Applications/MAMP/htdocs/test.php on line 38

You can also make it more silent doing just an echo or whatever you want. Also this way you can group a serie of functions as methods inside the class, and ensure they will be always accesible.

well good way to work with Closure is to wrap it with some helper class here is what i use

class Events {
    private $events;
    public function addEvents($eventName, Closure $c){
    $this->events[$eventName] = $c;
  }
   public function call($eventName, $args = array()){
    if (empty($args)){
        $this->events[$eventName]();
   }else {
     call_user_func_array($this->events[$eventName], $args);
     }
   }
}

usage

$events = new Events();
$events->addEvents('event', function(){
    echo 'hi'; 
 });
$events->call('event');

here codepad test link

Just write a regular named function? If you want a constant fixed name for it, that would seem to be the obvious answer.

If you absolutely have to have it dynamic as per your code, but not changeable from outside your control, I suggest putting it into a class. Have the actual variable set as to private, and provide a public getter for it, but not a setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM