Solved

how can I echo name using __get magic method

Posted on 2014-04-29
8
231 Views
Last Modified: 2014-05-01
<?php
class person{
  public $name;
  
  public function __construct($name,$age){
    $this->name=$name;
    $this->age=$age;
  }
  public function __get1($variable){
    echo '<h1>this is the variable: '.$variable.'</h1>';
  }
}

$obj=new person('jon',29);
echo '<br>name is: '.$obj->__get1($obj->name);

Open in new window



I do not think I am using magic_method properly because I switch __get to __get1 and code runs the same

how can I echo name using __get magic method
0
Comment
Question by:rgb192
  • 4
  • 2
  • 2
8 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 40031219
__get() magic method is used to get data from Inacessible property, that is, for instance, from a private property. Your $name is public, so it can be simply accessed with any method you use, giving it whatever name.

Set the property to private: __get1 will fail and __get will success.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40031721
Man Page Ref Here (always look this stuff up!):
http://www.php.net/manual/en/language.oop5.overloading.php#object.get
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40031745
Let's start with this.  It creates some output but it does not make much sense.
http://www.iconoun.com/demo/temp_rgb192.php

Line 6 declares the $name property to be public.  That is the default, so this line has no programmatic meaning.  It does no harm nor any good.

Conspicuous by its absence is any declaration for the $age property.  Without a visibility declaration, $age (and any other undeclared properties) is a public property of the object.

Line 8-12 creates the constructor that assigns the external values in the function definition statement, $name and $age, to object properties.

Line 14-17 creates the myGet() method.  The method takes an external variable named $variable and uses it in an echo statement.  It makes no reference to any of the object properties, working only with the variable in the function call.

Why did I change the name of __get1() to MyGet()?  Because PHP has reserved all function names starting with two underscores for internal PHP use.  You can't name your function that way if you want to write dependable PHP code.

<?php // demo/temp_rgb192.php
error_reporting(E_ALL);

class person
{
    public $name;
  
    public function __construct($name,$age)
    {
        $this->name=$name;
        $this->age=$age;
    }

    public function myGet($variable)
    {
        echo '<h1>this is the variable: '.$variable.'</h1>';
    }
}

$obj=new person('jon',29);

// SHOW THE OBJECT
var_dump($obj);

Open in new window

In a little while I'll try to show you how to use a getter function.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:rgb192
ID: 40031876
<?php // demo/temp_rgb192.php
error_reporting(E_ALL);

class person
{
    public $name;
  
    public function __construct($name,$age)
    {
        $this->name=$name;
        $this->age=$age;
    }

    public function myGet($variable)
    {
        echo '<h1>this is the variable: '.$variable.'</h1>';
    }
}

$obj=new person('jon',29);

// SHOW THE OBJECT
var_dump($obj);
echo 'I add this line to see if my ide has entered myGet method';

Open in new window

ide has not entered myGet method


okay __get() will work with private and ide will not enter __get1()
<?php
class person{
  private $name;
  
  public function __construct($name,$age){
    $this->name=$name;
    $this->age=$age;
  }
  public function __get1($variable){
    echo '<h1>this is the variable: '.$variable.'</h1>';
  }
}

$obj=new person('jon',29);
echo '<br>name is: '.$obj->__get1($obj->name);

Open in new window



Fatal error: Cannot access private property person::$name in C:\Users\Acer\Documents\NuSphere PhpED\Projects\noname309.php on line 15



I think I am not understanding magic method
for example
__tostring is 'magically used' when attempting to echo an object
__destruct is 'magically used' at the end of code

this is not magic:
$obj->__get($obj->name);
I am telling the $obj to enter its get method using parameter $obj->name
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40031884
this is not magic:
$obj->__get($obj->name);
I am telling the $obj to enter its get method using parameter $obj->name
I think it's not written out that way.  Give me a moment to try to put an example together using the earlier script.
ide has not entered myGet method
Of course not -- it was never called in place in the code.
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 40031914
Please see: http://www.iconoun.com/demo/temp_rgb192.php

Note that there is a magic method __get() defined in the Person class.  The magic method is called "magic" because it is invoked without being explicitly called in your code.  The constructor __construct() is also a magic method, just like __toString() and __Destruct, etc.

In PHP the definition of overloading is different from most languages.  Don't ask me why.

<?php // demo/temp_rgb192.php
error_reporting(E_ALL);

class Person
{
    protected $name;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age  = $age;
    }

    public function __get($var)
    {
        if (isset($this->$var))
        {
            echo '<h1>MAGIC METHOD __GET() CALLED FOR ' . "<i>$var</i>" . ': ' . $this->$var . '</h1>';
        }
        else
        {
            echo '<h1>MAGIC METHOD __GET() CALLED FOR UNDEFINED: ' . "<i>$var</i>" . '</h1>';
        }
    }
}

// CREATE AN INSTANCE OF THE PERSON CLASS
$obj = new person('jon',29);

// SHOW THE OBJECT INSTANCE OF THE PERSON CLASS
var_dump($obj);

// MUTATE THE AGE AND SHOW THE CLASS AGAIN
$obj->age = -14;
var_dump($obj);

// TRY TO GET THE $name PROPERTY
echo $obj->name;

// TRY TO GET AN UNDEFINED PROPERTY
echo $obj->pludgort;

Open in new window

Now after you have run that script, remove the __get() magic method as shown below and run it again.  You will get a fatal error.  The __get() method is there to give you a way to prevent a fatal run-time error when you (or more likely another programmer) makes a mistake.

<?php // demo/temp_rgb192.php
error_reporting(E_ALL);

class Person
{
    protected $name;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age  = $age;
    }

/*
    public function __get($var)
    {
        if (isset($this->$var))
        {
            echo '<h1>MAGIC METHOD __GET() CALLED FOR ' . "<i>$var</i>" . ': ' . $this->$var . '</h1>';
        }
        else
        {
            echo '<h1>MAGIC METHOD __GET() CALLED FOR UNDEFINED: ' . "<i>$var</i>" . '</h1>';
        }
    }
*/
}

// CREATE AN INSTANCE OF THE PERSON CLASS
$obj = new person('jon',29);

// SHOW THE OBJECT INSTANCE OF THE PERSON CLASS
var_dump($obj);

// MUTATE THE AGE AND SHOW THE CLASS AGAIN
$obj->age = -14;
var_dump($obj);

// TRY TO GET THE $name PROPERTY
echo $obj->name;

// TRY TO GET AN UNDEFINED PROPERTY
echo $obj->pludgort;

Open in new window

0
 
LVL 31

Assisted Solution

by:Marco Gasi
Marco Gasi earned 250 total points
ID: 40032397
rgb192, in my comment ID 40031219 I gave my opinion.

If you try what I said, you see it works. In you comment ID 40031876 you post two snippets: in the former you set $name variable as public, in the latter the variable is private.

__get allows to acces inaccessible properties (http://www.php.net/manual/en/language.oop5.magic.php) so, using your second snippet this way:

<?php
class person{
  private $name;
  
  public function __construct($name,$age){
    $this->name=$name;
    $this->age=$age;
  }
  public function __get($variable){
    echo '<h1>this is the variable: '.$variable.'</h1>';
  }
}

$obj=new person('jon',29);
echo '<br>name is: '.$obj->__get($obj->name);

Open in new window


Setting $name variable as private and using __get (not __get1) gives this output:

Output of script
The magic just resides in the fact you can access a private variable: in fact if you use $obj->get($obj->name) instead of $obj->__get($obj->name) you get the Fatal error:
Fatal error: Call to undefined method person::__get() in C:\xampp\htdocs\empty.php on line 15
0
 

Author Closing Comment

by:rgb192
ID: 40036059
thanks

The magic just resides in the fact you can access a private variable


this appeared more 'magical' because I did not see the word 'get'
// TRY TO GET THE $name PROPERTY
echo $obj->name;
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question