How to Add a New Method to a PHP Object on the Fly

How to add a new method to a php object on the fly?

You can harness __call for this:

class Foo
{
public function __call($method, $args)
{
if (isset($this->$method)) {
$func = $this->$method;
return call_user_func_array($func, $args);
}
}
}

$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();

Create objects on the fly without variable assignment with PHP

This only works if you are using a singleton-pattern for instanciating the object. If you are not aware of how to implement the singleton-pattern, you'll have to search around the web. But this way it would work:

className::getInstance()->someMethod();

EDIT

As stated by zerkms a factory-method would also be possible:

class ReflectionFactory
{
public static function factory($arguments)
{
return new ReflectionClass($arguments);
}
}

// Then in your code for example
ReflectionFactory::factory()->getConstants();

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

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'

?>

How to make a add a custom method on the fly in PHP

You can use the magic function __callStatic and add all the logic inside that function.

class Sample {
public static function __callStatic($name, $arguments) {
echo "method called:" . $method;
return false;
}
}

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
$object->property = 'Here we go';

var_dump($object);
/*
outputs:

object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Redefining PHP class functions on the fly?

Here's an idea of a possible solution you could try. Let the Cow and Human classes extend the Entity class. However, the Entity class would use a factory to instantiate the objects based on if the value was safe. Let's look at this in more detail:

/*
* Class Entity should not be able to be instantiated.
* It should contain a factory to instantiate the
* appropriate entity and an abstract function declaring
* the method that each entity will need to implement.
*/
abstract class Entity {

public static function factory($type) {
return (is_subclass_of($type, "Entity")) ? new $type() : FALSE;
}

abstract public function sayHi();

}

/*
* Human class extends Entity and implements the
* abstract method from Entity.
*/
class Human extends Entity {

public function sayHi() {
echo "Hello World!";
}

}

/*
* Cow class extends Entity and implements the
* abstract method from Entity.
*/
class Cow extends Entity {

public function sayHi() {
echo "Moo!";
}

}

Now to use this method, call the factory method and if all works well, it'll instantiate the proper class which will extend Entity.

$person = Entity::factory("Human");
$person->sayHi();

$cow = Entity::factory("Cow");
$cow->sayHi();

Using, is_subclass_of() will keep you safe because if the passed in value is not a class that extends Entity, you'll be returned a value of FALSE.

If you'd like to see the above code in action, copy the above php code and test it out on phpfiddle.org.

return objects on the fly in php

You can create a new object of stdClass(), assign its attributes and return it.

$x = new stdClass();
$x->attribute1 = "something";
$x->array1 = array(1,2,3);

var_dump($x);

return $x;

create a new class object on the fly using a foreach loop and the DirectoryIterator functions

If you have to access these XML objects later, better idea is to stroe them in associative array:

$xmlObjects = array();
$xmlObjects[$xmlFileObjName] = new XML();

php dynamically append method to class

try this instead (demo):

   <?php 

class stdClass1 extends \stdClass
{
private static $addedClosures = array();

public function __set($name, $value)
{
if ($value instanceof \Closure) {
self::$addedClosures[$name] = $value;
}
else {
parent::__set($name, $value);
}
}

public function __call($method, $arguments)
{
if (isset(self::$addedClosures[$method]))
return call_user_func_array(self::$addedClosures[$method], $arguments);
return call_user_func_array($method, $arguments);
}
}

class stdClass2 extends \stdClass
{

function stdRunMethod()
{
$obj = new stdClass1();
$obj->test = function () {
print_r('a simple function');
};
$obj->test();

$obj2 = new stdClass1();
$obj2->test();
}

}


Related Topics



Leave a reply



Submit