找回密码
 新猫注册
查看: 1357|回复: 0

php manual comments

[复制链接]
kernel 发表于 2009-5-4 18:40:32 | 显示全部楼层 |阅读模式
farzan at ifarzan dot com
05-Oct-2004 11:04
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:
<?
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:
<?
$element = 'aMemberVar';
print $foo->$element; // prints "aMemberVar Member Variable"
?>

or use functions:
<?
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:
<?
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:
<?
print $foo->{$otherObj->var};
print $foo->{$otherObj->func()};
?>

You can use mathods above to access member functions as well:
<?
print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"
print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"
?>

http://www.php.net/manual/en/language.oop5.php
您需要登录后才可以回帖 登录 | 新猫注册

本版积分规则

手机版|小黑屋|[漫猫]动漫论坛

GMT+8, 2024-11-21 17:53

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表