Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method in an std object in php

Tags:

Is it possible to add a method/function in this way, like

$arr = array(
    "nid"=> 20,
    "title" => "Something",
    "value" => "Something else",
    "my_method" => function($arg){....}
);

or maybe like this

$node = (object) $arr;
$node->my_method=function($arg){...};

and if it's possible then how can I use that function/method?

like image 524
The Alpha Avatar asked Jul 16 '12 11:07

The Alpha


People also ask

How to take value from object in PHP?

The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object. When an object is made, it has some properties. An associative array of properties of the mentioned object is returned by the function. But if there is no property of the object, then it returns NULL.

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How to check object type in PHP?

The is_object() function checks whether a variable is an object. This function returns true (1) if the variable is an object, otherwise it returns false/nothing.

How to check object or array in PHP?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.


1 Answers

This is now possible to achieve in PHP 7.1 with anonymous classes

$node = new class {
    public $property;

    public function myMethod($arg) { 
        ...
    }
};

// and access them,
$node->property;
$node->myMethod('arg');
like image 94
Krishnaprasad MG Avatar answered Sep 26 '22 01:09

Krishnaprasad MG