Padraig
Padraig

Reputation: 3707

How to declare a php variable to be constant

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

e.g.

$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.

Upvotes: 3

Views: 277

Answers (4)

Shushant
Shushant

Reputation: 1635

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

Upvotes: 1

aleation
aleation

Reputation: 4844

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.

Upvotes: 1

Spudley
Spudley

Reputation: 168655

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.

Upvotes: 0

Zathrus Writer
Zathrus Writer

Reputation: 4331

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.

Upvotes: 5

Related Questions