Classes and Objects

2013 年 3 月 27 日5360

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 ;

public ;

function aMemberFunc() {

print 'Inside `aMemberFunc()`';

}

}

;

?>

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

<?php

$element = 'aMemberVar';

print // prints "aMemberVar Member Variable"

?>

or use functions:

<?php

function getVarName()

{ return 'aMemberVar'; }

print // 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);

print // Prints "aMemberVar Member Variable"

// Prints "aMemberVar Member Variable"

?>

You can use members of other objects as well:

<?php

};

print ()};

?>

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

<?php

// Prints "Inside `aMemberFunc()`"

// Prints "Inside `aMemberFunc()`"

?>

0 0