Related
I have some problems with my class Model and other classes so I made this simple example to explain my problem :
class person{
public static $a = "welcome";
public function __construct(){
}
public static function getobject()
{
$v = new person();
return $v;
}
}
class student extends person{
public static $b = "World";
}
$st = student:getobject();//this will return person object but I want student object
echo $st->$b; // There is an error here because the object is not student
So I want to know what to write instead $v = new person(); to get the object of the last inherited class.
Use the late static binding's static keyword.
public static function getobject()
{
$v = new static();
return $v;
}
So, with student::getobject() you get an instance of student.
To retrieve the static (but why?) $b propriety, you can do $st::$b, or simply student::$b.
$model = new static($variable);
All these are within a method inside a class, I am trying to technically understand what this piece of code does. I ran around in the Google world. But can't find anything that leads me to an answer. Is this just another way of saying.
$model = new static $variable;
Also what about this
$model = new static;
Does this mean I'm initializing a variable and settings it's value to null but I am just persisting the variable not to lose the value after running the method?
static in this case means the current object scope. It is used in late static binding.
Normally this is going to be the same as using self. The place it differs is when you have a object heirarchy where the reference to the scope is defined on a parent but is being called on the child. self in that case would reference the parents scope whereas static would reference the child's
class A{
function selfFactory(){
return new self();
}
function staticFactory(){
return new static();
}
}
class B extends A{
}
$b = new B();
$a1 = $b->selfFactory(); // a1 is an instance of A
$a2 = $b->staticFactory(); // a2 is an instance of B
It's easiest to think about self as being the defining scope and static being the current object scope.
self is simply a "shortcut name" for the class it occurs in. static is its newer late static binding cousin, which always refers to the current class. I.e. when extending a class, static can also refer to the child class if called from the child context.
new static just means make new instance of the current class and is simply the more dynamic cousin of new self.
And yeah, static == more dynamic is weird.
You have to put it in the context of a class where static is a reference to the class it is called in. We can optionally pass $variable as a parameter to the __construct function of the instance you are creating.
Like so:
class myClass {
private $variable1;
public function __construct($variable2) {
$this->variable1 = $variable2;
}
public static function instantiator() {
$variable3 = 'some parameter';
$model = new static($variable3); // <-this where it happens.
return $model;
}
}
Here static refers to myClass and we pass the variable 'some parameter' as a parameter to the __construct function.
You can use new static() to instantiate a group of class objects from within the class, and have it work with extensions to the class as well.
class myClass {
$some_value = 'foo';
public function __construct($id) {
if($this->validId($id)) {
$this->load($id);
}
}
protected function validId($id) {
// check if id is valid.
return true; // or false, depending
}
protected function load($id) {
// do a db query and populate the object's properties
}
public static function getBy($property, $value) {
// 1st check to see if $property is a valid property
// if yes, then query the db for all objects that match
$matching_objects = array();
foreach($matching as $id) {
$matching_objects[] = new static($id); // calls the constructor from the class it is called from, which is useful for inheritance.
}
return $matching_objects;
}
}
myChildClass extends myClass {
$some_value = 'bar'; //
}
$child_collection = myChildClass::getBy('color','red'); // gets all red ones
$child_object = $child_collection[0];
print_r($child_object); // you'll see it's an object of myChildClass
The keyword new is used to make an object of already defined class
$model = new static($variable);
so here there is an object of model created which is an instance of class static
What is the difference between two codes?
Extends;
<?php
require_once 'example.class.php';
Class First extends Example
{}
?>
Normal calling;
<?php
require_once 'example.class.php';
Class First
{
public $example;
function __construct()
{
$this->example = new Example();
}
}
?>
I know some difference for example using protected pharase.
But this is not enough in my opinion.
The first one, the object First will have the same properties/functions of Example class. Like:
class Example
{
public function a()
{
}
}
class First extends Example
{
public function b()
{
}
}
if you instance two objects $ex1, $ex2:
$ex1 = new Example();
$ex1->a(); // this is valid
$ex1->b(); // this is invalid because Example doesn't have "b" function
$ex2 = new First();
$ex2->a(); // this is valid
$ex2->b(); // this is valid too, because First inherits Example members + its own
on the second code, you're creating an instance of example so you must access that variable to be able to call Example method.
one better example:
class Person
{
public $name;
public function say($message)
{
echo $this->name . " says " . $message;
}
}
class Teacher extends Person
{
public function say($message)
{
// note that Teacher has a name even this is not declared here.
echo $this->name . " says " . $message;
}
public function teach($what)
{
// note that Teacher has a name even this is not declared here.
echo $this->name . " is teaching " . $what;
}
}
See the output:
$john = new Person();
$john->name = "John Doe";
$john->say("hello world!");
/*
$john->teach("Portuguese"); // invalid, person doesn't teach anything.
*/
$chuck = new Teacher();
$chuck->name = "Chuck Norris";
$chuck->say("hello universe!");
$chuck->teach("Fighting"); // valid because Teacher has method "teach"
Extends
This is object inheritance. First inherits Example members, so First is Example.
An instance of First can call a method of Example and one of itself.
Creating an instance of Example
This just creating an object of Example. First methods can use other objects in order to achieve its goals.
I believe you need to get more in touch with object-oriented programming in order to learn more about its concepts and you'll understand things like this.
In the first example, First extends Example so it has all its methods and properties.
In your second example you are just setting a property to be an object of the class Example. At least I assume that is what you want to do because the way you wrote it, $example is only defined in the scope of the constructor so it is never available anywhere.
I assume that for your second example you would want something like:
Class First
{
protected $example;
function __construct()
{
$this->example = new Example();
}
}
jeroen is correct, but it also determines which attributes of the Example class can be accessed from the First class. For example, if the Example class has 2 methods which are private or protected, and you don't extend, the First class will not be able to access them.
Consider the following:
class Example
{
public $foo;
protected $bar;
}
Class First extends Example
{
public function __construct()
{
$this->foo = 'FOO1'; // Works because public scope
$this->bar = 'BAR1'; // Works even though scope is protected, because we extended the class
}
}
Class Second
{
public example;
function __construct()
{
$this->example = new Example();
$this->example->foo = 'FOO1'; // Works because public scope
$this->example->bar = 'BAR2'; // Fails because protected scope and we did not extend the class
}
}
// However, from the calling code, I am also limited
$first = new First();
$first->foo = 'NEW_FOO1'; // Works because public scope
$first->bar = 'NEW_BAR1'; // Fails because protected scope
$second = new Second();
$second->example->foo = 'NEW_FOO2'; // Works because public scope
$second->example->bar = 'NEW_BAR2'; // Fails because protected scope
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';
}
}
?>
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.