+ 9
Can someone explain me how to use "$this=>"
I can't understand the thing $this in php someone help please
7 Answers
+ 1
$this is a predefined variable which is used to calling a object.
for example
<?php
class num{
public $a=5;
public function show(){
echo $this->a;
}
}
$ob=new num ();
$ob->show ();
?>
+ 6
$this is a class member and it is mainly used to refer properties/objects of a class.
To learn about theĀ $this variable is to ask PHP what it is.Ā
For example:
print is_array($this);
print is_object($this);
+ 6
Hi! When working with classes $this is reference to the current object. in other if you've declare a public property $name, to access it you need to use $this->name. meaning your refere to the property $name.
It cannot be use outside of a class, nor in a static method in which you will have to use self:: instead.
Let say you have a class:
<?php
class Person
{
// a property $name = 'John';
public $name;
// then for instance you have a function that return a name.
public function getName()
{
//to access $name, use $this.
return $this->name; // will return John, if you use $name, an error will be thrown, $name is undefined.
}
}
// Same as if you instatiate the class Person
$name = new Person();
// to get the name you need to call getName method, we then use $name as it an object of the class Person thus can access it public method
$name->getName() // will return John, here $name act like $this.
To access an object (not static) in a class you use $this, and self:: if it's static and to access outside of the class you instantiate a new object $newObject and use it to access methods and property of a class $newObject->theObjectMethod().
+ 2
Print is_array($this=>)
+ 1
Thanks John Dooe
+ 1
youre welcome!
0
suhail Rathod