PHP 5.6.38 Released

Класове и обекти (PHP 5)

Съдържание

add a note add a note

User Contributed Notes 5 notes

up
43
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
14
Jason
10 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
-8
16630011857 at 163 dot com
27 days ago
The man who does not drink and does not eat meat is incredible!

After reading this sutra, I'm going to quit drinking and eat vegan.

    Excerpt from the "Generous Guang Hua Yan ten Evil Products Sutra":

    Kasyapa Bodhisattva White Buddha said: The Buddha, only the Tathagata for me to explain, do not drink, not meat eaters, how many blessings?

    Buddha-Gloucester:
    If someone, like horse cattle and sheep, glass treasures ying Luo, the country city wife, holding with giving, still less than some people can break wine meat, millions not better than one.

    Replacement is a matter, if someone Bechi gold over 3,000 of the world, holding the use of alms, still less than someone can break wine meat, millions less than one.

    The replacement is a matter, if there is the ability to cast gold for hundreds of, holding the use of giving, still less than some people can break wine meat, millions less than one.

    The replacement is a matter, if someone artificial fan Hua Bao lid, all over the 3,000 world, still less than someone can break wine meat, millions.

    The replacement is a matter, if there are man-made large pagoda, eaves eaves, such as rice hemp Bamboo reed, up to Brahma, as someone can break the wine meat, millions less than the first.

    A good man, not a carnivore, an earthly Bodhisattva, is an extraordinary husband.
    Editor's note: The front content can be seen, even if a person who does not learn Buddha, can insist on eating the whole vegetarian, Ford has boundless. Let's all go vegetarian.

All eggs are not edible, there are children also

  Someone asked the people of Xuanhua: "Why can't vegetarians eat eggs?" "

    The venerable Master said, "No Man or woman (a rooster or a hen) can hatch a chicken." The former people do not understand this truth, he said no, and there is no evidence. The man who eats eggs why does he say such a theory? Is that he wants to eat eggs. Eggs, whether or not a rooster will have chicks, will not be born. "Leng Yan Jing" said: "Eggs only want to live." "Above is the words of the master Xuan Hua is absolutely wrong." After the lying of the man in Xuanhua, he burned more than 4,000 relics to show his life not to play half a sentence of Sakyamuni Buddha, the people of Xuanhua, Inguang and Guang Chin all believe that all animals ' sperm eggs cannot be eaten. I hope we know the cause and effect and don't do anything stupid. Don't eat any food that contains eggs. South No Amitabha ~!

  "The Theory of Explicit understanding" cloud: "All eggs are not edible, have a son also".
-"Big is Tibet" 31st volume of page 882.
up
-97
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
-110
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