Solved

how can I echo name using __get magic method

Posted on 2014-04-29
8
224 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 30

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 108

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 108

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
 

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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

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 108

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 30

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now