0

any way to add new method to an object in php such as javascript?

in javascript we can extend an js obj like this

var o={};
o.test1 = function(){...}

how to do it in php? please see my code bellow:

<?php

class a{
    function test(){
        echo 'hello';
    }
}

$var= new a;

// I want to add a new method fo $var
// .... how to extend $var here ?

$var->test1();  // world

// placeholder
// placeholder
// placeholder
// placeholder
// placeholder
// placeholder
// placeholder
mingfish_004
  • 1,385
  • 2
  • 18
  • 26
  • 1
    I've to comment that it makes 0 sense to do this in PHP. Adding methods dynamically is in most cases just plain silly. However, you do it by utilising PHP's magic __call method, or use PHP extension called classkit that lets you define methods dynamically. But, you should really rethink your app design and completely avoid the need for mentioned functionality (naturally, it really might be the case where you simply can't do it without it, so my comment might also be pure BS). – N.B. May 05 '14 at 08:18
  • 1
    possible duplicate of [How to add a new method to a php object on the fly?](http://stackoverflow.com/questions/2938004/how-to-add-a-new-method-to-a-php-object-on-the-fly) – kennypu May 05 '14 at 08:20

1 Answers1

1

you can extend your object : (note : this is not my code, I just copy this code is from documentation php extends class)

<?php

class foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP est super' . PHP_EOL;
    }
}

class bar extends foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Affiche : 'Foo: baz'
$foo->printPHP();       // Affiche : 'PHP est super'
$bar->printItem('baz'); // Affiche : 'Bar: baz'
$bar->printPHP();       // Affiche : 'PHP est super'

?>
Mimouni
  • 3,564
  • 3
  • 28
  • 37