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
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'
?>