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::
Related
Trying to get some data from one method in side static method(using it inside a other class) but I get the 'Using $this when not in object context in...' error.
Below a basic example
class mClass{
public $someVar = 'Hello world...';
public function passFunc(){
$give = $this->someVar;
return $give;
}
public static function showFunc(){
$show = self::passFunc();
return $show;
}
}
mClass::showFunc();// show error: Using $this when not in object context in...
You can't use $this, when you are working with static variables. $this is a pointer to the current object, but static variables belongs to class.
A class method (or static function) isn't tied to a particular instance of your class, i.e. it doesn't have $this although self is available.
A class method can access static properties or methods, but accessing anything else within the class will raise an error. It's best to look at static methods as a means to organize functions; as such, they operate in between external functions and instance methods.
In your case, you'd have to create an instance inside your static method:
public static function showFunc()
{
$o = new self;
$show = $o->passFunc();
return $show;
}
I've created a class that calls an object in the "__construct" how can i make this object available through out the class.
class SocialMedia { function __construct() { $object = "whatever"; } }
how can I access $object in the other functions (which are static) from with in the class.
I've tried to use "$this->object" but I get an error "$this when not in object context" when I try to call it from my other static functions.
Use
self::$object = 'whatever'
instead and read the PHP Manual on the static keyword
On a sidenote, statics are death to testability, so you might just was well forget what you just learned and use instance variables instead.
Try defining your object inside the scope of the class, right above the function. So, as an example:
class SocialMedia { public $object; function __construct() { $object = "whatever"; } }
Or you could try defining it as "public static" instead of just "public". As an example, this:
class SocialMedia { public static $object; function __construct() { $object = "whatever"; } }
make it static:
class SocialMedia {
protected static $object;
function __construct() {
self::$object = "whatever";
}
}
If $object is not static then you have a problem. You need to be able to refernce a specific instance of the class. Youll need to pass the actual instance of SocialMedia to its static method or come up with some other shenanigans:
public static function someMethod(SocialMedia $instance, $args)
{
// do stuff with $instance->object and $args
}
public function methodThatUsesStaticMethod($args)
{
self::someMethod($this, $args);
}
If $object is static then you can use the scope resolution operator to access it as others have mentioned:
public static $object;
public static function someMethod($args)
{
$object = self::$object;
// do stuff with $object and $args
}
But then you have another issue... What happens if no instance of SocialMedia has been created yet and so SocialMedia::$object is not yet set?
You could make your class a singleton (OOP Patterns in PHP Manual) but that really isn't any better solution if you want testability and/or dependency injection. No matter how you suggarcoat it you are after a global variable and sooner or later you'll find out all the troubles they bring.
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';
}
}
?>
<?php
class Popular
{
public static function getVideo()
{
return $this->parsing();
}
}
class Video
extends Popular
{
public static function parsing()
{
return 'trololo';
}
public static function block()
{
return parent::getVideo();
}
}
echo Video::block();
I should definitely call the class this way:
Video::block();
and not initialize it
$video = new Video();
echo $video->block()
Not this!
Video::block(); // Only this way <<
But:
Fatal error: Using $this when not in object context in myFile.php on line 6
How to call function "parsing" from the "Popular" Class?
Soooooooory for bad english
As your using a static method, you cant use $thiskeyword as that can only be used within objects, not classes.
When you use the new keyword, your creating and object from a class, if you have not used the new Keyword then $this would not be available as its not an Object
For your code to work, being static you would have to use the static keyowrd along with Scope Resolution Operator (::) as your method is within a parent class and its its not bounded, Use the static keyword to call the parent static method.
Example:
class Popular
{
public static function getVideo()
{
return static::parsing(); //Here
}
}
What does $this mean in PHP?
paamayim-nekudotayim - Scope Resolution
http://php.net/manual/en/language.oop5.static.php
change return $this->parsing(); to return self::parsing();
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.