When would you use the $this keyword in PHP? - php

When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.
Also the keyword $this can only be used within a method?
An example would be great to show when you can use $this.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

The most common use case is within Object Oriented Programming, while defining or working within a class. For example:
class Horse {
var $running = false;
function run() {
$this->running = true;
}
}
As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.

You would only use $this if you are doing Object Oriented programming in PHP. Meaning if you are creating classes. Here is an example:
class Item {
protected $name, $price, $qty, $total;
public function __construct($iName, $iPrice, $iQty) {
$this->name = $iName;
$this->price = $iPrice;
$this->qty = $iQty;
$this->calculate();
}
}

$this is used to make a reference to the current instance of an object.
So you can do things like:
class MyClass {
private $name;
public function setName($name) {
$this->name = $name;
}
//vs
public function setName($pName) {
$name = $pName;
}
}
Also another cool use is that you can chain methods:
class MyClass2 {
private $firstName;
private $lastName;
public function setFirstName($name) {
$this->firstName = $name;
return $this;
}
public function setLastName($name) {
$this->lastName = $name;
return $this;
}
public function sayHello() {
print "Hello {$this->firstName} {$this->lastName}";
}
}
//And now you can do:
$newInstance = new MyClass2;
$newInstance->setFirstName("John")->setLastName("Doe")->sayHello();

It's used in Object-oriented Programming (OOP):
<?php
class Example
{
public function foo()
{
//code
}
public function bar()
{
$this->foo();
}
}
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).

Used for when you want to work with local variables.
You can also read more about it from here.
function bark() {
print "{$this->Name} says Woof!\n";
}

One time I know I end up using the this equivalent in other languages is to implement a 'Fluent' interface; each class method which would otherwise return void instead returns this, so that method calls can be easily chained together.
public function DoThis(){
//Do stuff here...
return $this;
}
public function DoThat(){
//do other stuff here...
return $this;
}
The above could be called like so:
myObject->DoThis()->DoThat();
Which can be useful for some things.

$this is used when you have created a new instance of an object.
For example, imagine this :
class Test {
private $_hello = "hello";
public function getHello () {
echo $this->_hello; // note that I removed the $ from _hello !
}
public function setHello ($hello) {
$this->_hello = $hello;
}
}
In order to access to the method getHello, I have to create a new instance of the class Test, like this :
$obj = new Test ();
// Then, I can access to the getHello method :
echo $obj->getHello ();
// will output "hello"
$obj->setHello("lala");
echo $obj->getHello ();
// will output "lala"
In fact, $this is used inside the class, when instancied. It is refered as a scope.
Inside your class you use $this (for accessing *$_hello* for example) but outside the class, $this does NOT refer to the elements inside your class (like *$_hello*), it's $obj that does.
Now, the main difference between $obj and $this is since $obj access your class from the outside, some restrictions happens : if you define something private or protected in your class, like my variable *$_hello*, $obj CAN'T access it (it's private!) but $this can, becase $this leave inside the class.

no i think ur idea is wrong.. $this is used when refers to a object of the same class.. like this
think we have a variable value $var and in THAT instance of that object should be set to 5
$this->var=5;

The use $this is to reference methods or instance variables belonging to the current object
$this->name = $name
or
$this->callSomeMethod()
that is going to use the variable or method implemented in the current object subclassed or not.
If you would like to specifically call an implementation of of the parent class you would do something like
parent::callSomeMethod()

Whenever you want to use a variable that is outside of the function but inside the same class, you use $this. $this refers to the current php class that the property or function you are going to access resides in. It is a core php concept.

<?php
class identity {
public $name;
public $age;
public function display() {
return $this->name . 'is'. $this->age . 'years old';
}
}
?>

Related

What is the true definition of $this in PHP?

I currently am using PHP and was reading the PHP manual but still have a problem with $this.
Is $this something global or is it is just another variable name to build objects on?
Here is an example:
public function using_a_function($variable1, $variable2, $variable3)
{
$params = array(
'associative1' => $variable1,
'associative2' => $variable2,
'associative3' => $variable3
);
$params['associative4'] = $this->get_function1($params);
return $this->get_function2($params);
}
How would $this work for the return function? I guess I am confused on how this function builds. I understand building the associate array part with a name being a valuekey names => value, but $this throws me off on this example.
$this is only used in object oriented programming (OOP) and refers to the current object.
class SomeObject{
public function returnThis(){
return $this;
}
}
$object = new SomeObject();
var_dump($object === $object->returnThis()); // true
This is used inside the object to reach member variables and methods.
class SomeOtherClass{
private $variable;
public function publicMethod(){
$this->variable;
$this->privateMethod();
}
private function privateMethod(){
//
}
}
It is refered to as the Object scope, lets use an example class.
Class Example
{
private $property;
public function A($foo)
{
$this->property = $foo;
// we are telling the method to look at the object scope not the method scope
}
public function B()
{
return self::property; // self:: is the same as $this
}
}
We can now instance our object and use it in another way also:
$e = new Example;
$e::A('some text');
// would do the same as
$e->A('some other text');
This is just a way of accessing the scope of the Object because methods cannot access other method scopes.
You can also extend a class and use the parent:: to call the class extension scope, for example:
Class Db extends PDO
{
public function __construct()
{
parent::__construct(....
Which would access the PDO construct method rather than its own construct method.
In your case, the method is calling other methods that are in the object. Which can be called using $this-> or self::

PHP OOP - Accessing property value is returning empty

I have the following class, and for some reason it's not accessing the test property. Why is this? I'm new to OOP, so please be easy on me. Thanks
class Test {
private $test;
function __contruct() {
$this->test = "test";
}
static function test() {
echo $this->test;
}
}
$test = new Test;
$test::test();
Because static methods are callable without an instance of the object
created, the pseudo-variable $this is not available inside the method
declared as static.
PHP Documentations.
Good morning.
It seems you have 3 issues with your code.
There is a syntax error at constructor line change it from __contruct to __construct.
Change test function visibility to public
Access your function with the -> instead of ::
To elaborate further on the above answers: Static methods and variables are not linked to any particular instance of the object, this is why you have to call test with $test::test(). This also means that you cannot access an instance variable from without a static method and it doesn't really make sense to do so (If you had multiple instances of the object with different values set for that variable, how would the interpreter know which instance/value to use?)
If you want to have a field accessible from a static method then you have to make the field static as well. So, if you wanted to have $test accessible from your static method test() then you'd have to write your function as something along these lines:
class Test {
private static $test;
function __contruct() {
Test::$test = "test";
}
public function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
However, it doesn't really make sense to be initialising a static field like that in your constructor. So you'd more likely be wanting to do something like:
class Test {
private static $test = "test";
function __contruct() {
}
public static function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
Or, if you don't actually require test() to be static then you could just make it an instance method:
class Test {
private $test = "test";
function __contruct() {
$this->$test = "test"
}
public function test() {
echo $this->$test;
}
}
$test = new Test;
$test->test();

Use Class property inside of a method's function

I'm trying to use myVar inside my of a method's function. I have already tried adding global but still nothing. I know this is probably basic but I can't seem to find it.
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
Whenever I try using $this I get this error: 'Using $this when not in object context in...'
You should use $this->myVar
See the PHP Documentation - The Basics
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
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
Update:
In your new code sample, myInnerFunction is a nested function and is not accessible until the myFunction method is called. Once the myFunction method is called, the myInnerFunction becomes part of the global scope.
Maybe this is what you are looking for:
class myClass{
public $myVar;
public function myFunction() {
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
Inner functions like myInnerFunction are always global in scope, even if they are defined inside of a member function in a class. See this question for another similar example
So, to PHP, the following are (almost) equivalent:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
And
class myClass{
public $myVar;
public function myFunction() {
}
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
Hopefully the second example illustrates why $this is not even in scope for myInnerFunction. The solution is simply to pass the variable as a parameter to the function.
Pass it as an argument to the inner function.
You can use ReflectionProperty:
$prop = new ReflectionProperty("SimpleClass", 'var');
Full example:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
$prop = new ReflectionProperty("SimpleClass", 'myVar');
}
}
}
The solution above is good when you need each instance to have an own value. If you need all instances to have a same you can use static:
class myClass
{
public static $myVar = "this is my var's value";
public function myClass() {
echo self::$myVar;
}
}
new myClass();
see here

How do I check in PHP that I'm in a static context (or not)?

Is there any way I can check if a method is being called statically or on an instantiated object?
Try the following:
class Foo {
function bar() {
$static = !(isset($this) && $this instanceof self);
}
}
Source: seancoates.com via Google
"Digging it out of debug_backtrace()" isn't too much work. debug_backtrace() had a 'type' member that is '::' if a call is static, and '->' if it is not. So:
class MyClass {
public function doStuff() {
if (self::_isStatic()) {
// Do it in static context
} else {
// Do it in object context
}
}
// This method needs to be declared static because it may be called
// in static context.
private static function _isStatic() {
$backtrace = debug_backtrace();
// The 0th call is to _isStatic(), so we need to check the next
// call down the stack.
return $backtrace[1]['type'] == '::';
}
}
Checking if $this is set won't work always.
If you call a static method from within an object, then $this will be set as the callers context. If you really want the information, I think you'll have to dig it out of debug_backtrace. But why would you need that in the first place? Chances are you could change the structure of your code in a way so that you don't.
I actually use this line of code on all my scripts,it works well and it prevents errors.
class B{
private $a=1;
private static $static=2;
function semi_static_function(){//remember,don't declare it static
if(isset($this) && $this instanceof B)
return $this->a;
else
return self::$static;
}
}
The use of instanceof is not paranoia:
If class A call class B statically function $this may exist on the A scope;
I know it's pretty messed up but php does it.
instanceof will fix that and will avoid conflicting with classes that may implement your "semi-static" functions.
Test for $this:
class Foo {
function bar() {
if (isset($this)) {
echo "Y";
} else {
echo "N";
}
}
}
$f = new Foo();
$f->bar(); // prints "Y"
Foo::bar(); // prints "N"
Edit: As pygorex1 points out, you can also force the method to be evaluated statically:
class Foo {
static function bar() {
if (isset($this)) {
echo "Y";
} else {
echo "N";
}
}
}
$f = new Foo();
$f->bar(); // prints "N", not "Y"!
Foo::bar(); // prints "N"
Testing isset($this) wasn't working for me, as mentioned by troelskn "$this will be set as the callers context."
abstract class parent
{
function bar()
{
if( isset( $this ) ) do_something();
else static::static_bar();
}
function static static_bar()
{
do_something_in_static_context();
}
}
class child extends parent
{
...
}
$foo = new child();
$foo->bar(); //results in do_something()
child::bar(); //also results in do_something()
In my case, I have a parent class with a object and static context function that performs the same task within a child class. isset( $this ) was always returning true, however, I noticed that while $this switches between being class child in object context and calling(?) class on static context, the wonderful __class__ magic constant, remained as class parent!
Shortly there-after finding the function is_a, we can now test if we're in static context:
if( is_a($this, __CLASS__) ) ...
Returns true on object context, false on static context.
Please test for your own implementations, as I'm only testing this for my specific scenario (a unique case of inheritance calling) in 5.3.
Unfortunately (for my case) I am yet unable to find a way to call the static_bar() since $this and static are referring to a separate class, and __class__ is referring to the parent class. What I need is a way to call child::static_bar()...
This is an old question, but I'll add an alternative answer.
There are two magic methods
__call($name, $arguments)
is triggered when invoking inaccessible methods in an object context.
__callStatic($name, $arguments)
is triggered when invoking inaccessible methods in a static context.
<?php
class MethodTest
{
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0
Outputs
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
Check whether $this is defined
<?
class A {
function test() {
echo isset($this)?'not static':'static'; }
}
$a = new A();
$a->test();
A::test();
?>
Edit: beaten to it.
It's 2022 now, with php 7.4, 8: you can/should no longer be vague about the context a method will be called in.
If a method is not declared static, 7.4 will warn you, 8 will fatal error.
If a method is declared static, $this is never available.
<?php
class C {
public function nonStaticMethod() {
print isset($this) ? "instance ": "static\n";
}
public static function staticMethod() {
print isset($this) ? "instance ": "static\n";
}
}
// php 8: Fatal error: Uncaught Error: Non-static method Foo::bar() cannot be called statically
// php 7.4: Deprecated: Non-static method Foo::bar() should not be called statically
C::nonStaticMethod();
C::staticMethod();
$f = new C();
$f->nonStaticMethod();
// `$this` is still not defined. It works without the instance context,
// even though you called it from an instance.
$f->staticMethod();
Other hacks are available, of course.
Create a static variable and change it in the constructor.
private static $isInstance = false;
public function __construct()
{
self::$isInstance = true;
}
Now you can check it
public function myMethod()
{
if (self::$isInstance) {
// do things
}
}
Just return the class as new within the function.
return new self();

What does the variable $this mean in PHP?

I see the variable $this in PHP all the time and I have no idea what it's used for. I've never personally used it.
Can someone tell me how the variable $this works in PHP?
It's a reference to the current object, it's most commonly used in object oriented code.
Reference: http://www.php.net/manual/en/language.oop5.basic.php
Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
Example:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
This stores the 'Jack' string as a property of the object created.
The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:
print isset($this); //true, $this exists
print gettype($this); //Object, $this is an object
print is_array($this); //false, $this isn't an array
print get_object_vars($this); //true, $this's variables are an array
print is_object($this); //true, $this is still an object
print get_class($this); //YourProject\YourFile\YourClass
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this); //delicious data dump of $this
print $this->yourvariable //access $this variable with ->
So the $this pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:
Class Dog{
public $my_member_variable; //member variable
function normal_method_inside_Dog() { //member method
//Assign data to member variable from inside the member method
$this->my_member_variable = "whatever";
//Get data from member variable from inside the member method.
print $this->my_member_variable;
}
}
$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.
If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.
It's possible for $this to be undefined if the context has no parent Object.
php.net has a big page talking about PHP object oriented programming and how $this behaves depending on context.
https://www.php.net/manual/en/language.oop5.basic.php
I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.
Example:
Class A
{
public $myname; //this is a member variable of this class
function callme() {
$myname = 'function variable';
$this->myname = 'Member variable';
echo $myname; //prints function variable
echo $this->myname; //prints member variable
}
}
output:
function variable
member variable
It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.
From the PHP docs:
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).
Lets see what happens if we won't use $this and try to have instance variables and
constructor arguments with the same name with the following code snippet
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
It echos nothing but
<?php
class Student {
public $name;
function __construct( $name ) {
$this->name = $name; // Using 'this' to access the student's name
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
this echoes 'Tom'
when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.
another version of meder's example:
class Person {
protected $name; //can't be accessed from outside the class
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
// this line creates an instance of the class Person setting "Jack" as $name.
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack");
echo $jack->getName();
Output:
Jack
This is long detailed explanation. I hope this will help the beginners. I will make it very simple.
First, let's create a class
<?php
class Class1
{
}
You can omit the php closing tag ?> if you are using php code only.
Now let's add properties and a method inside Class1.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
The property is just a simple variable , but we give it the name property cuz its inside a class.
The method is just a simple function , but we say method cuz its also inside a class.
The public keyword mean that the method or a property can be accessed anywhere in the script.
Now, how we can use the properties and the method inside Class1 ?
The answer is creating an instance or an object, think of an object as a copy of the class.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
$object1 = new Class1;
var_dump($object1);
We created an object, which is $object1 , which is a copy of Class1 with all its contents. And we dumped all the contents of $object1 using var_dump() .
This will give you
object(Class1)#1 (2) { ["property1"]=> string(15) "I am property 1" ["property2"]=> string(15) "I am property 2" }
So all the contents of Class1 are in $object1 , except Method1 , i don't know why methods doesn't show while dumping objects.
Now what if we want to access $property1 only. Its simple , we do var_dump($object1->property1); , we just added ->property1 , we pointed to it.
we can also access Method1() , we do var_dump($object1->Method1());.
Now suppose i want to access $property1 from inside Method1() , i will do this
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
$object2 = new Class1;
return $object2->property1;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
we created $object2 = new Class1; which is a new copy of Class1 or we can say an instance. Then we pointed to property1 from $object2
return $object2->property1;
This will print string(15) "I am property 1" in the browser.
Now instead of doing this inside Method1()
$object2 = new Class1;
return $object2->property1;
We do this
return $this->property1;
The $this object is used inside the class to refer to the class itself.
It is an alternative for creating new object and then returning it like this
$object2 = new Class1;
return $object2->property1;
Another example
<?php
class Class1
{
public $property1 = 119;
public $property2 = 666;
public $result;
public function Method1()
{
$this->result = $this->property1 + $this->property2;
return $this->result;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
We created 2 properties containing integers and then we added them and put the result in $this->result.
Do not forget that
$this->property1 = $property1 = 119
they have that same value .. etc
I hope that explains the idea.
This series of videos will help you a lot in OOP
https://www.youtube.com/playlist?list=PLe30vg_FG4OSEHH6bRF8FrA7wmoAMUZLv
$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).
$this is a special variable and it refers to the same object ie. itself.
it actually refer instance of current class
here is an example which will clear the above statement
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
It refers to the instance of the current class, as meder said.
See the PHP Docs. It's explained under the first example.
Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.
this keyword should be preceded with a $ symbol.
In case of this operator, we use the -> symbol.
Whereas, $this will refer the member variables and function for a particular instance.
Let's take an example to understand the usage of $this.
<?php
class Hero {
// first name of hero
private $name;
// public function to set value for name (setter method)
public function setName($name) {
$this->name = $name;
}
// public function to get value of name (getter method)
public function getName() {
return $this->name;
}
}
// creating class object
$stark = new Hero();
// calling the public function to set fname
$stark->setName("IRON MAN");
// getting the value of the name variable
echo "I Am " . $stark->getName();
?>
OUTPUT:
I am IRON MAN
NOTE:
A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

Categories