Accessing php class object

0
250
php class object
php class object

In this post, my focus is to access the member properties (variables) and methods (functions) within php class object in a 4(four) logical but sweet ways.

More than 15years Ago, farzan said:

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 php classes and objects.

I used this class example #1 as reference for all accessing method examples:

Example #1: a php oop class

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

$foo = new Foo;
?> 

Ways of Accessing PHP Class Object

I have covered four (4) basic Difference ways you may want to access members of a php class object unlike the normal accessing procedure that you already know or have used.

access member variables with another variable:

You can access member variables in a php oop class object using another variable as name

Example #2: Accessing member variable in object using another variable as name

<?php
$element = 'aMemberVar';
print $foo->$element; // prints "aMemberVar Member Variable"
?> 

functions:

Hence, You may create function that must return a value of the similar name of the member property variable that you wish to access

Example #3: using a function to access member variable

<?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”.

Example #4: Using a function to access member method

<?php
function getVarName()
{
     return 'aFuncName';
}

print $foo->{$foo->{getVarName()}}();
?>

Using a constant:

Now, you can use a constant or literal as well to access member variable in an php class object

Example #5: Using a constant to access member property

<?php
define('MY_CONSTANT', 'aMemberVar');
print $foo->{MY_CONSTANT}; // Prints "aMemberVar Member Variable"
print $foo->{'aMemberVar'}; // Prints "aMemberVar Member Variable"
?> 

A member of another object:

You can use members of other objects as well, to access member functions:

Example #6: Using an object member of another object

<?php
print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"
print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"
?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here