PHP Code: usage of this keyword
public f开发者_高级运维unction __construct($template = '', array $data = array())
{
if ($template !== '') {
$this->setTemplate($template);
}
if (!empty($data)) {
foreach ($data as $name => $value) {
$this->$name = $value;
}
}
}
Got this from the devshed composite view tutorial (http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/). Anyway, I'm a bit confuse on, $this->$name = $value;
statement.
I usually use $this
for class's properties and/or when invoking class's methods within the said class. Plus the statement have two $
's. Which is weird! So is $this->$name = $value
referring to the $name
defined in the foreach loop? If so can someone explain this usage or logic behind this?
Thank you in advance.
The $name in
$this->$name = $value
Sets the variable defined as $name to $value
E.g. if $name = 'user', then this is the equivalent to
$this->user = value;
This type of syntax is often used (as demonstrated above) in foreach loops to set object values.
Note: Each time $this->variable_name is called, if 'variable_name' is not already defined as a property of the object, the magic __set function is called, with 'variable_name' passed as the argument.
See http://php.net/manual/en/language.oop5.overloading.php
I didn't go to the link you posted but reading the code.
I will give you an example:
// If $data has the following values
array(
'firstname' => 'my first name',
'surname' => 'my surname'
)
The code will have 'firstname' and 'surname' as a public property of the class. The values for $this->firstname
will be 'my first name'. The value of $this->surname
will be 'my surname'.
$name contain the name of property
nothing else
instead of just mentioning the property statically it is pointing to the variable which contain the name of property
$name='someproperty';
$this->$name;
Let as assume that the current value of $name is "foo". then $this->name will return exactly the same as $this->foo.
精彩评论