I am wondering what is the difference between $this->name and $this->$name? Also does $this have to be strictly named this or can it be anything?
$this is a reserved variable name and can not be used for anything else. It specifically points you to the object your are currently working in. You have to use $this because you do not know what variable object will be assigned to.
$this->name refers to the current class's variable name
$this->$name refers to the class variable of whatever the value of $name is. Thus
$name = "name";
echo $this->$name; // echos the value of $this->name.
$name = "test";
echo $this->$name; // echos the value of $this->test
$this is a reserved name used in PHP to point to the current instance of the class you are using it in (quoting) :
The pseudo-variable $this is available
when a method is called from within an
object context. $this is a reference
to the calling object (usually the
object to which the method belongs,
but possibly another object, if the
method is called statically from the
context of a secondary object).
When using $this->name, you are accessing the property with the name name of the current object.
When using $this->$name, $name is determined before accessing the property -- which means you'll access the property which name is contained in the $name local variable.
For instance, with this portion of code :
$name = 'abc';
echo $this->$name;
You'll actually echo the content of the abc property, as if you had written :
echo $this->abc;
When doing this, you are using variable variables (quoting) :
Class properties may also be accessed
using variable property names. The
variable property name will be
resolved within the scope from which
the call is made. For instance, if you
have an expression such as $foo->$bar,
then the local scope will be examined
for $bar and its value will be used as
the name of the property of $foo. This
is also true if $bar is an array
access.
This question just popped up after an update. I liked the question, so I thought I'd add my own example of the difference.
class Test
{
public $bar = 'bar';
public $foo = 'foo';
public function __construct()
{
$bar = 'foo';
$this->bar; // bar
$this->$bar; // foo
}
}
Related
I have the following code:
<?php
class myclass {
public $var;
public $foo = $this->var;
}
// ...etc
When I execute this, I get the following error:
( ! ) Fatal error: Constant expression contains invalid operations in
E:\public_html\index.php on line 4
How can I call this variable not outside of class? (I mean, I don't want to define it like the following):
$myclass = new myclass();
$myclass->foo = $myclass->var;
Class variables can only be defined with constant values.
To make a dynamic assignment, you need to do it in your constructor:
class myclass {
public $var = "Hey there";
public $foo;
public function __construct()
{
$this->foo = $this->var;
}
}
Once you create an instance of this class $foo will have a value of "Hey there".
From the docs:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
class User{
protected $dates =[
'created'
];
public function __construct(){
foreach( $this->dates as $date){
$property = $this->{$date};
$this->{$date} = new DateTime($property);
}
}
}
1) Is using "this" with "date" variable in the foreach loop inside a class specific to php or a general oops concept?
2) why do we need curly braces with "this" can't we simply write $this->date ?
$this->{$date} is a variable variable. It uses the value of $date as the name of a property to access. So when $date = "created" (as it is when iterating through the $this->dates property), it's equivalent to $this->created.
You don't need the curly braces if the expression is just a variable name, you can write $this->$date; but if it's a more complex expresion you need the braces, e.g. $this->{$date . "_field"} would be equivalent to$this->created_field. But many programmers use the braces consistently, just to make the code clearer and cause a warning if they forget the$`.
You need the $ to make it use a variable as the property name. If you just write $this->date it looks for the date property, not the created property.
Using dynamic property names like this is available in many scripting languages; for instance, you can do it in Javascript with this[date]. It's not generally available in statically-typed languages like C++.
$this->{$date} , assuming your date is '2018-08-13', for example, you're trying to acess $this->2018-08-13.
I think what you want is
foreach($this->dates as $date){
//DO SOMETHING LIKE INITIATE THE OBJ
$obj->date = date("Y-m-d H:i:s"); //If you want current time
// OR
$obj->date = $date; //For the value on $date
}
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo.
For Example:
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
$this->var is used when you have actual property declared in class ($var above)
whereas $this->$date in your case will be used when you are not declaring property in the class and would like to still use it has a class property...
In order to use $this->dates you will need to declare a class variable like
class {
public $dates;
public function __construct($d){
$this->dates = $d;
}
}
$this->{$date} will be interpreted as $this->created
I have been confused by $this.I know $this->somevaribale used for refering global values...But i have seen a code like
class ClassName
{
private $array; //set up a variable to store our array
/*
* You can set your own array or use the default one
* it will set the $this->array variable to whatever array is given in the construct
* How the array works like a database; array('column_name' => 'column_data')
*/
function __construct($array = array('fruit' => 'apple', 'vegetable' => 'cucumber')) {
$this->array = $array;
}
/*
* Loops through the array and sets new variables within the class
* it returns $this so that you may chain the method.
*/
public function execute() {
foreach($this->array AS $key => $value) {
$this->$key = $value; //we create a variable within the class
}
return $this; //we return $this so that we can chain our method....
}
}
Here $this is called alone ...Am really confused with this..When i remove $this and replaced with $this->array i get error..
So my question is what is the use of calling $this alone and what it represents.
Thanx for the help.
$This is a reference for PHP Objects. You can learn more about objects and how $this works in the PHP manual here.
A class is a kind of "blueprint" of an object, and vice versa, and object is an instance of a class. When $this is used within the class, it refers to itself.
$hi = new ClassName();
$hi->execute()->method()->chaining()->is_like_this();
$hi refers to a ClassName object, and the function execute() returns the object itself.
$ha = $hi->execute();
// $ha refers to a ClassName object.
Method chaining (fluent interfaces) enables one to tidy up the code if one normally calls many methods of that object:
$hi->doSome();
$hi->doAnotherThing();
$hi->thirdMethodCall();
$hi->etcetera();
will become
$hi->doSome()
->doAnotherThing()
->thirdMethodCall()
->etcetera();
A couple of corrections to the terms you use:
$this is a reference to the "current" object, not "global values"
you're not "calling" anything here; functions are called, you're just using $this (which, again, is a variable holding an object)
So, return $this returns the current object as return value of the method. This is usually just done to facilitate fluent interfaces, a style where you can write code like:
$foo->bar()->baz()
Because bar() returns an object (the $this object), you can call its method baz() right afterwards.
Possible duplicate of Reference - What does this symbol mean in PHP?
What does it mean when you have something like this $this->_view->id ?
It is within a class (obviously) and I understand the $this. I get how to use one -> to refer to a property or call a method. But what about when there are two -> in one thing?
The fuller code is:
$viewid = ($this->_view) ? $this->_view->id : null;
I'm guessing the overall gist is: Set $viewid to either (1) the value of $this->_view->id or (2) null, depending on whether $this->_view is TRUE or not. But I don't get the (1) bit.
Also, is it conventional to use an underscore (_view) to show a property or a method?
Thanks.
This means that there is an object stored within an object.
$this->_view refers to an object called $_view within. So within $_view object $this->id would refer to its $id variable.
So calling $this->_view->id calls for variable $id in an object $_view that is stored in your current object (since you said its $this).
Detailed:
class firstClass {
public $_view;
}
class secondClass{
public $id=1;
}
$a=new firstClass();
$a->_view=new secondClass();
echo $a->_view->id; // prints 1
$viewid = ($this->_view) ? $this->_view->id : null;
It means if view object is available for current object, then set its id to $viewid, otherwise set it to null.
for example $this is current object of UserClass. $this->_view is object of view of UserClass and $this->_view->id is id of view object.
Generally, for private or protected member of class, we start with _
$id is attached to an object returned by the function function _view.
The underscore is a preference,
I have a method in a variable named class that I need to call dynamically, how can I call this:
$foo = "object"
Where object is a specific class
How do I call this in PHP?
$foo::method()
The wording of the question is confusing but from what I understand, if you want to set $foo to a specific class, lets call it Foo you can do this:
$foo = new Foo;
Here is our class Foo
class Foo {
public $aMemberVar = 'aMemberVar Member Variable';
public $aFuncName = 'aMemberFunc';
function aMemberFunc() {
print 'Inside `aMemberFunc()`';
}
}
If you want to access a class variable Foo and set it to a variable you can do this:
$myVar = 'aMemberVar';
print $foo->$myVar //prints "aMemberVar Member Variable"
Also to clarify $foo::method() implies that $foo is a static class, and static classes cannot be instantiated but they can call on its class method method() by using the scope resolution operator (::)
Hope this helps.
$$foo::method();
See PHP variable variables