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
2
  • 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). Commented May 5, 2014 at 8:18
  • 1
    possible duplicate of How to add a new method to a php object on the fly? Commented May 5, 2014 at 8:20

1 Answer 1

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'

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.