What does $this mean in PHP? [duplicate] - php

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP: self vs this
Hello,
Could you help me understanding the meaning of the PHP variable name $this?
Thank you for your help.

$this refers to the class you are in.
For example
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
Hope this helps.

You might want to have a look at the answers in In PHP5, what is the difference between using self and $this? When is each appropriate?
Basically, $this refers to the current object.

$this is a protected variable that's used within a object, $this allows you to access a class file internally.
Example
Class Xela
{
var age; //Point 1
public function __construct($age)
{
$this->setAge($age); //setAge is called by $this internally so the private method will be run
}
private function setAge($age)
{
$this->age = $age; //$this->age is the variable set at point 1
}
}
Its basically a variable scope issue, $this is only allowed within a object that has been initiated and refers to that object and its parents only, you can run private methods and set private variables where as out side the scope you cannot.
also the self keyword is very similar apart from it refers to static methods within class, static basically means that you cant use $this as its not an object yet, you must use self::setAge(); and if that setAge method is declared static then you cannot call it from an instant of that object / object
Some links for you to get started:
http://php.net/manual/en/language.variables.scope.php
http://php.net/manual/en/language.oop5.static.php
How to explain 'this' keyword in a best and simple way?
When to use self over $this?

Related

Using $this when not in object context php

I just started learning OOPS in php. I wrote a simple program for implementing inheritance. I am getting a fatal error of $this when not in object context. Can anyone explain me this error, what does it mean?
here is my code:
<?php
class human{
public $gender;
public function _construct($gender)
{
$this->gender=$gender;
echo $this->get_gender();
}
public function get_gender()
{
return $this->gender;
}
}
class person extends human{
public $name;
public $surname;
public static function set_name($name)
{
$this->name=$name;
}
public static function set_surname($surname)
{
$this->surname=$surname;
}
public static function get_name()
{
return $this->name;
}
public static function get_surname()
{
return $this->surname;
}
}
$john = new person('male');
$john->set_name('John');
$john->set_surname('Williams');
echo $john->get_name().' '.$john->get_surname().'is a '.$john->get_gender();
?>
There are two problems here:
You have defined your methods as static. You should not do that as they are not, they depend on being called on an object as you want to use the objects non-static properties.
You have a typo in your constructor function. The correct name for the constructor is __construct, notice the two _ at the beginning.
In a static function, $this does not exist. You can refer to the class itself with self::. So, instead of $this->surname, use self::surname. As noted below, this will change your error to a new error as it requires the variables to be declared static as well.
Of course, you really need to figure out WHY you made those functions static. Should they be static?
You're trying to access the $this property from a static method. You cannot do this, as anything static can be accessed without instantiating the class, therefore the $this variable would not make sense, as you are not in an actual class instance.
The this keyword refers to the current object you are working with, e.g. if you were to make 5 instances of person, each $this would refer to that specific instance of person, and you could change each objects properties freely.
When you use static you are not referring to any instance, you are simply accessing static variables and calling static methods of that class. All these variables and methods are 'class wide'. That means if you change the static property in one instance of the class, the static property will change in all the classes.
Another way to imagine this is, take when calling the new keyword, you create a new instance of the object. Every instance will have its own copy of all the properties and methods you describe in the class, EXCEPT for the static ones. Imagine that when you access a static method or a static property you are accessing one object always.
That's why it would not make sense to access $this from a static context. You are not referring to any specific instance, only the class itself.
I hope I've explained this well enough, it's a very important concept to grasp in OOP, and it does give some people a lot of trouble to understand the concept.

Call a private $var via a static method in php without instanciating any object [duplicate]

I have this method that I want to use $this in but all I get is: Fatal error: Using $this when not in object context.
How can I get this to work?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
This is the correct way
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
Use self:: instead of $this-> for static methods.
See: PHP Static Methods Tutorial for more info :)
You can't use $this inside a static function, because static functions are independent of any instantiated object.
Try making the function not static.
Edit:
By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Only static functions can be called within the static function using self:: if your class contains non static function which you want to use then you can declare the instance of the same class and use it.
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
The accessor this refers to the current instance of the class. As static methods does not run off the instance, using this is barred. So one need to call the method directly here. The static method can not access anything in the scope of the instance, but access everything in the class scope outside instance scope.
It's a pity PHP doesn't show a descriptive enough error. You can not use $this-> inside a static function, but rather use self:: if you have to call a function inside the same class
In the static method,properties are for the class, not the object.
This is why access to static methods or features is possible without creating an object.
$this refers to an object made of a class, but $self only refers to the same class.
Here is an example of what happens when a method of a class is called in a wrong way. You will see some warnings when execute this code but it will work and will print: "I'm A: printing B property". (Executed in php5.6)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
It seams that the variable $this, used in a method which is called as a static method, points to the instance of the "caller" class. In the example above there is $this->property used in the A class which points to a property of the B.
EDIT:
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).
PHP > The Basics

static variable not accessible via an object or $this but static functions are accessible via $this or object in PHP

<?php
class c1
{
public static function f1()
{
return "hello";
}
public static $a=10;
public function f2()
{
echo $this->f1(); //prints "hello"
echo $this->a;//ERROR:Undefined property: c1::$a in C:\wamp\www\class_in_php\example5.php on line 14
}
}
$obj1=new c1;
$obj1->f2();
?>
Why can't we access a static variable of a class using $this or an object of that class???
But we can access a static function of that class using $this or an object of that class.
What is the reason behind such a phenomenon?
You should use self:: instead of $this-> to access static members.
The reason is that $this refers to the current instance of the class, while static members are part of the class itself, not of the instance.
A static variable belongs not to an "instance" but to the class itself. When you have in actual "instance" of the class at runtime, then and only then does the $this pointer make sense: it means "this instance that I find myself inside right now"... how could you use the $this pointer to reference something that doesn't exist outside of an instance?
When I first learned C++ it was with (Metacomco I think) a system that actually used a huge pile of C preprocessor macros to simulate objects and it was very enlightening to see and hence understand that the $this (this in C++) is in fact just an extra parameter passed as the first parameter to all method functions:
this->foo("Hello");
this->bar(42, "Finished");
is actually executed like this:
foo(this_ptr, "Hello");
bar(this_ptr, 42, "Finished");
and inside the foo() function any reference to a method variable such as:
this->status
is nothing more than a reference to a pointer dereferenced variable:
this_ptr->status
So you can see that trying to access a static variable from a this pointer is going to blow because it just isn't a member of that particular chunk of memory. That's how things "used to work" but I think the explanation is still a good one.
Hope that help!
:)
Why can't we access a static variable of a class using $this or an object of that class? But we can access a static function of that class using $this or an object of that class.
Well, we can, however you used the wrong syntax.
Wrong:
echo $this->a;
Right:
$this::$a;
As c1::$a is a static class variable, you need to use the right syntax, that is with double-colon :: and then the dollar-sign ($) to denote the variable: $this::$a.
However, do not get fooled by that syntax too easy, because the reason that
$this->f1()
works while c1::f1() is a static function is because of backwards compatibility as before PHP version 5 there were no static class methods (as those explicitly defined by the static keyword) and with the very first PHP 5 version -> could be used to call static class methods.
However to access static class variables via $this is a PHP 5.3+ syntax feature, so much newer.
Example code (run against multiple PHP versions):
<?php
/**
* #link http://stackoverflow.com/a/24059368/367456
*/
class c1
{
public static function f1()
{
return "hello";
}
public static $a = 10;
public function f2()
{
echo $this->f1(); // prints "hello"
echo $this->a; // Strict Standards: Accessing static property c1::$a as non static
echo $this::$a; // prints "10" (PHP <= 5.2.17: Parse error)
}
}
$obj1 = new c1;
$obj1->f2();

Diffrences of $this:: and $this-> in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: self vs. $this
I've found that I can call class methods by $this:: prefix. example:
class class1 {
public function foo()
{
echo "1";
}
public function bar()
{
$this::foo();
//in this example it acts like $this->foo() and displays "2"
//using self::foo() displays "1"
}
}
class class2 {
public function foo()
{
echo "2";
}
public function bar()
{
class1::bar();
}
}
$obj = new class2();
$obj->bar(); // displays "2"
class1::bar(); // Fatal error
I want to know whats the diffrence of calling method with $this-> and $this:: prefixes.
ps:
There is a page about diffrence of $this->foo() and self::foo() in this link:
When to use self over $this?
The answer that you linked tells you exactly what you're looking for ;).
Basically, there are two concepts that some people have a tough time differentiating in programming languages: objects and classes.
A class is abstract. It defines a structure of an object. The properties and methods that an object would contain, if an object were built from that class. Creating an object is what you do when you call new class1(). This is instructing PHP to create a new object with all of the properties and methods on the class1 class.
The important thing to note about creating an object is that it also has its own scope. This is really where $this vs static:: (note: do not use self:: or $this::, please use static:: (more on this later)) come in to play. Using $this is instructing PHP to access the properties and methods of your current object. Using static:: is instructing PHP to access the properties and methods of the base class that your object is constructed from.
Here's an example:
class MyClass {
public $greeting;
public static $name;
public greet() {
print $this->greeting . " " . static::$name;
}
}
$instance1 = new MyClass();
$instance1->greeting = 'hello';
$instance2 = new MyClass();
$instance2->greeting = 'hi';
MyClass::$name = 'Mahoor13';
$instance1->greet();
$instance2->greet();
I didn't test the above, but you should get:
hello Mahoor13
hi Mahoor13
That should give to a general idea of the difference between setting a class property and setting an instance property. Let me know if you need additional help.
Edit
$this:: appears to just be a side effect of the way that PHP handles scopes. I would not consider it valid, and I wouldn't use it. It doesn't appear to be supported in any way.
the $this-> is called from instance , so you have to have an instance of the object to use this call.
but $this:: is a static method inside the class you can call it without instance so you do not need to alloc an instance of the class to call it like
myclass::doFoo();
public static function doFoo(){ .... }
and the do function should be static function to call it like this or the php will give error in the newer versions

Using static in PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: Static and non Static functions and Objects
Why would I use the static key word in php? Is it only to create "good" code or does it have some advantages as well?
function useThisAsStatic(){}
static function useThisAsStatic(){}
public static function useThisAsStatic(){}
public function useThisAsStatic(){}
To clarify the question; all above methods can be used by calling
Object::useThisAsStatic();
And thus suggests that there is no difference in declaring a method to be static.
Is it only to create "good" code
Actually it's to create bad code.
Read why
And this article is more specified about static (thanks to Gordon)
Static functions mean you can call them without instantiating the class (creating the object) first.
Useful in certain situations, but static functions cannot make use of the local members of the class outside of that function.
static means belonging to the Class. You can call a static method or field. Without creating instance of the class.
class NewClass {
public $public_var = "I'm public property!";
public static $static_var = "I'm static property!";
public function public_method()
{
return "I'm public method!";
}
public static function static_method()
{
return "I'm static method!";
}
}
Now you can call NewClass::$static_var and NewClass::static_method() without creating NewClass instance.
While to call public_var and public_method you should create new instance of class:
$c = new NewClass();
echo $c->public_var;
echo $c->public_method();

Categories