php class and object, comprehensive php class and object, Shopinson, Shopinson

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.

Below examples listed 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;
?> 

4 Difference ways to access members of an object

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

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

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

3. 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"
?> 

4. 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()`"
?>
function getVarName()
{
     return 'aFuncName';
}

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

this was written far back before the emergence of latest php now but still compatible according to php.net documentary.

0 Comments

Leave a reply

Your email address will not be published. Required fields are marked *

*

shopinson-logo-32

©2020 Shopinson: complete guide to programming language

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account