PHP 7.2.7 Released
add a note add a note

User Contributed Notes 4 notes

up
41
farzan at ifarzan dot com
13 years ago
PHP 5 is very very flexible in accessing member variables and member functions. These access methods maybe look unusual and unnecessary at first glance; but they are very useful sometimes; specially when you work with SimpleXML classes and objects. I have posted a similar comment in SimpleXML function reference section, but this one is more comprehensive.

I use the following class as reference for all examples:

<?php
class Foo {
    public
$aMemberVar = 'aMemberVar Member Variable';
    public
$aFuncName = 'aMemberFunc';
   
   
    function
aMemberFunc() {
        print
'Inside `aMemberFunc()`';
    }
}

$foo = new Foo;
?>

You can access member variables in an object using another variable as name:

<?php
$element
= 'aMemberVar';
print
$foo->$element; // prints "aMemberVar Member Variable"
?>

or use functions:

<?php
function getVarName()
{ return
'aMemberVar'; }

print
$foo->{getVarName()}; // prints "aMemberVar Member Variable"
?>

Important Note: You must surround function name with { and } or PHP would think you are calling a member function of object "foo".

you can use a constant or literal as well:

<?php
define
(MY_CONSTANT, 'aMemberVar');
print
$foo->{MY_CONSTANT}; // Prints "aMemberVar Member Variable"
print $foo->{'aMemberVar'}; // Prints "aMemberVar Member Variable"
?>

You can use members of other objects as well:

<?php
print $foo->{$otherObj->var};
print
$foo->{$otherObj->func()};
?>

You can use mathods above to access member functions as well:

<?php
print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"
print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"
?>
up
15
Jason
9 years ago
For real quick and dirty one-liner anonymous objects, just cast an associative array:

<?php

$obj
= (object) array('foo' => 'bar', 'property' => 'value');

echo
$obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

?>

... no need to create a new class or function to accomplish it.
up
-72
Ashley Dambra
4 years ago
Here a simple class 'stdObject' that give us the possibility to create dynamic classes and the possibility to add and execute methods thing that 'stdClass' don't let us do.  Very useful if you extends it to a controller on MVC Design pattern. Let users create own classes.

I have also post this class on http://www.php.net/manual/en/language.types.object.php

<?php
class stdObject {
    public function
__construct(array $arguments = array()) {
        if (!empty(
$arguments)) {
            foreach (
$arguments as $property => $argument) {
               
$this->{$property} = $argument;
            }
        }
    }

    public function
__call($method, $arguments) {
       
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
       
if (isset($this->{$method}) && is_callable($this->{$method})) {
            return
call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new
Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;

$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
   
echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
   
$stdObject->age = $age;
};

$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
    if (!
$value instanceOf Closure) {

       
$obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
           
$stdObject->{$func_name} = $value;
        };

       
$obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
           
return $stdObject->{$func_name};
        };

    }
}

$obj->setName("John");
$obj->setAdresse("Boston");

$obj->getInfo();
?>
up
-91
0x174[d0t]14[at]gmail[d0t]com
3 years ago
A little trick for create an anonymous object  (exactly an half-anonymous object :D aka "_") who can handle methods.

<?php

class _
{
    public function
__construct( array $cfg){
        foreach(
$cfg as $k=>$v){
           
$this->{$k}=$v;
        }
    }
   
    public function
__call( $fn, array $args){
        if(isset(
$this->{$fn})){
           
array_unshift($args, $this);
           
call_user_func_array( $this->{$fn}, $args);
        }
    }
}

$o = new _(array(
   
"color"=>"red",
   
"run"=>function($this){
        echo
"My color is : ".$this->color;
    }
));

$o->run();

?>
To Top