xdevel2000
xdevel2000

Reputation: 21444

Code equivalence between Javascript and PHP

I'm trying to learn PHP and I wish to know if there are some function equivalence constructs:

In JS I can do:

var t = function() {};
t();

myObj.DoStuff = function() {} // here I add a method at run-time
myObj.DoStuff();
myObj["DoStuff"]();

var j =  myObj.DoStuff;
j();

and so other things with function evaluation.

In Js objects are associative arrays so every properties is accessible with the subscript notation...

Can I add a method at run-time to a class template so next its object instances can have it?

In JS I can do that via a prototype function property.

Upvotes: 1

Views: 138

Answers (2)

Ivo Sabev
Ivo Sabev

Reputation: 5240

It is possible, but it is not healthy and not a good practice or something you would like to do on a daily bases. JavaScript and PHP are differently organized you will use Classes and Methods in PHP, where in JavaScript they are objects and functions.

Here is an example of what you are trying to do written in 5.2+ where there are no anonymous functions:

<?php

/*
var t = function() {};
t();
*/

function _t() {
    echo '<br>T';
}

$t = '_t';
$t();

/*
myObj.DoStuff = function() {} // here I add a method at run-time
myObj.DoStuff();
myObj["DoStuff"]();

var j =  myObj.DoStuff;
j();
*/
class myObj {
    var $doStuff = '';
}

function _DoStuff() {
    echo '<br>Do Stuff';
}

$myObj = new myObj();
$myObj->doStuff = '_DoStuff';
$j = $myObj->doStuff;
$j();

?>

In 5.3+ they introduced anonymouse functions so you can even do that

$t = function() {
    echo 'T';
}
$t();

More about Anonymous functions here - http://php.net/manual/en/functions.anonymous.php

I would advise you to read more about Variable function names which is mostly helpful.

You can also dynamically inject functions inside a Class which is the second thing you are trying to do, but it is not a good idea in general. One guy did some work on that here - http://www.gen-x-design.com/archives/dynamically-add-functions-to-php-classes/

Upvotes: 2

RaYell
RaYell

Reputation: 70444

Basically, it's not possible in PHP. There are some tricks that allows you in some cases add a functionality to new objects (like using magic __call method) but nothing close to what you can do with JavaScript prototypes.

If you need something similar in a server side language you may want to learn Python instead of PHP.

Upvotes: 0

Related Questions