tags:

views:

51

answers:

2

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.

A: 

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.

RaYell
Keep in mind that PHP 5.3 introduces full lambda functions, so this is indeed possible.
mattbasta
Lambdas doesn't allow you to add methods to existing objects. They allow you to create an inline anonymous functions.
RaYell
+2  A: 

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/

Ivo Sabev
Why can I pass for:$myObj = new myObj();$myObj->doStuff = function(){};$j = $myObj->doStuff;$j();and I can't invoke directly $myObj->doStuff();So I can't understand why if I have a function that returns an array I can't do:myFunc()[2]; // it takes the 3° elements...Is PHP a dynamic language or not???May be I'd look to Python...
xdevel2000
It is what it is.
Ivo Sabev