分享

PHP: 类与对象

 妙行莲花 2018-07-21
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()`'
?>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多