PHP 7.4.6 Released!
add a note add a note

User Contributed Notes 2 notes

up
32
farzan at ifarzan dot com
15 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
1
rjtarpura at gmail dot com
1 month ago
We can also access function like this. It looks strange but it works.

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

$foo = new Foo;

function
getVarName()
{
     return
'aFuncName';
}

print
$foo->{$foo->{getVarName()}}();
To Top 重庆肘时彩官网 黑龙江快乐十分开奖号 走势图 天津十一选五开奖结果历史 吉林11选五专家推荐 内蒙古11选五大遗漏 西安配资 云南11选5100期走势图 贵州11选5综合走势图 江苏十一选五走势图 北京赛车公式官方网 北京快3最新开奖结果查询 证券投资上证指数 江苏彩票快3 股票配资公司先问尚牛在线 河南泳坛夺金开奖直播 贵州十一选五购买平台 山西11选5前三走势