I'm primarily a JS developer, using PHP for that server-side kick and I'm looking to see if there's an method in PHP similar to the JS:
var something = {
action1: function() { alert('Fire 1!'); },
action2: function() { alert('Fire 2!'); },
action3: function() { alert('Fire 3!'); }
}
Then allowing me to call like:
something.action2(); // Alerts 'Fire 2!'
It's for a relatively small app I'm working on and I'd like to avoid building classes. Since PHP is such a small part I'd like to keep it as similar in code-style as possible.
PHP does not have the same form of objects that JavaScript does, as PHP is a class-based language, while JavaScript is a prototype-based language. What this essentially means is that PHP creates objects by instantiating a class. JavaScript, however, has objects that are then cloned to create new objects.
If you wish to keep your code understandable, I'd recommend using PHP classes:
class SomeClass {
function alert($string) {
// Do something
}
function action1() {
$this->alert('Fire 1!');
}
function action2() {
$this->alert('Fire 2!');
}
function action3() {
$this->alert('Fire 3!');
}
}
$something = new SomeClass();
$something->action2(); // Runs the action2 function of your object
Using an associative array and anonymous functions (must have at least PHP 5.3) would work for you:
$arr = array(
'action1' => function() { echo "Fire 1
"; },
'action2' => function() { echo "Fire 2
"; },
'action3' => function() { echo "Fire 3
"; }
);
$arr['action1'](); // Fire 1
Keep in mind that you will not able to access the other functions or items of the array from the functions using $this
(this
in JavaScript).
Perhaps if you gave us more details on what you are looking to do, we could give some better examples.
Or perhaps a static class?
<?php
class something {
public static function action1 () {
echo 'Fire 1';
}
public static function action2 () {
echo 'Fire 2';
}
public static function action3 () {
echo 'Fire 3';
}
}
something::action1();
something::action2();
something::action3();
This would work (assuming you want to create 3 alerts like that :P).
<?php
//Array of Functions
$a = array
(
'action1' => function() { echo "<script>alert('Fire 1!');</script>"; },
'action2' => function() { echo "<script>alert('Fire 2!');</script>"; },
'action3' => function() { echo "<script>alert('Fire 3!');</script>"; }
);
$a['action1'](); // Fire 1
$a['action2'](); // Fire 2
$a['action3'](); // Fire 3
?>
A modification of Tim Cooper's answer
$o = (object) array(
'action1' => function() { echo "Fire 1
"; },
'action2' => function() { echo "Fire 2
"; },
'action3' => function() { echo "Fire 3
"; }
);
$o->action2();