This question already has answers here:
PHP: What if I call a static method in non-static way
(3 answers)
Closed 6 years ago.
I am trying to wrap my head around the static keyword in PHP. Here I wrote a small piece of code where my person1 instance of Human can call a static method called sayRealname(). But when I try to call a public static variable it gives an error. What is the reason for that?
class Human{
public static $age=34;
public static $name='humpty dumpty';
protected static $realname='al';
public static function sayRealname(){
echo self::$age;
}
}
$person1=new Human();
echo $person1->name; // error
$person1->sayRealname(); // prints 34
When you're accessing static content, you need to use the static operator ::.
On the other hand, the arrow operator -> is meant to be used in an instance context, which belongs to the particular instance upon it's being called.
You can read more about this in this part of the documentation.
Related
This question already has answers here:
PHPUnit - Use $this or self for static methods?
(3 answers)
When should I use 'self' over '$this'?
(23 answers)
Closed 3 years ago.
I was messing around and discovered that you could actually call static methods with $this->method()
And it got me a bit confused and curious about the differences between the 3 ways (that I know of) to call static methods
$this->method();
static::method();
self::method();
Now, I think I understand the difference between the latter two, but what about the first one?
It is important to understand the behavior of static properties in the context of class inheritance:
Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.
Static properties defined ONLY in the parent class will share a COMMON value.
declare(strict_types=1);
class staticparent {
static $parent_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromparent';
static::$both_distinct = 'fromparent';
}
}
class staticchild extends staticparent {
static $child_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromchild';
static::$both_distinct = 'fromchild';
static::$child_only = 'fromchild';
}
}
$a = new staticparent;
$a = new staticchild;
More on https://www.php.net/manual/en/language.oop5.static.php
self using for static method and variable in class
$this using for non static method and variable
static generally using call child class of static methods or variable
For example late static
For example late static binding
This question already has answers here:
Is it possible to declare a method static and nonstatic in PHP?
(6 answers)
Closed 3 years ago.
I have a class "A" containing a static method. Now I want a copy of that class(whether by extension or not) except I need that static method to become non-static in the new class.
Any ideas are welcome. Thanks in advance.
I tried extending but when redeclaring the method as non-static I got an error:
class A {
protected $key = null;
static function methodX($args) {
// ...
}
}
class B extends A {
protected $key = "key";
public function methodX($args) {
// ...
return $this->key;
}
}
The actual flavor of overriding is linked with an object. Overriding is when we pass a child class object to a parent class reference variable but the static methods are associated with class they are not linked with an object so we can’t override a static method
The answer here is no. What is the reason? Well, because non-static member variables of a class always belong to an object – meaning that every object has it’s own personal copy of non-static member variables (also known as instance variables). And, static functions have no object to work with since they belong to the class as a whole. Remember that you can call a static function without an object – and for that exact reason a static function can not call instance variables.
you can override only static method to static method.
But you can't, you have to override it as static or create a new function for non-static in your child.
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 4 years ago.
class ModelFile extends CoreModel{
public $var;
public $var2;
public static function getId() {
$this->var = '123';
}
}
I have above model. I am facing issue while using assigned variable.
The error I get on above code is
Fatal error: Using $this when not in object context
Any idea of this issue?
You cannot access $this in static methods because they don't belong to any instance, but to the whole class instead. In your case, just remove static keyword.
This question already has answers here:
PHP: Static and non Static functions and Objects
(5 answers)
Closed 8 years ago.
I am still learning OOP PHP and I keep swapping and changing between the following way of calling methods within an object
$obj = new Model();
$obj->method($param);
against
Model::method($params);
I understand the difference when I within the method as I can use $this in the first example, and I have to use self:: in the second.
Which is the correct way and what are the reasons of using each way
The reason I ask is I cannot find a suitable search term to research. I am currently reading a book on OOP and it will probably tell at some point, but would be nice to know now.
Foo::bar() calls the static class method, while $foo->bar() calls the instance method on an object. These are two completely different things. You do not need an object instance to call Foo::bar(), and in fact you do not have access to instance data when doing so. Foo::bar() is essentially nothing else but a regular function call like bar(), except that the function is attached to a class.
Instance methods act on a specific object instance:
class User {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public static function hi() {
// no access to $this->name here, since static
// methods are not bound to specific instances
echo 'Hi';
}
}
$dave = new User('Dave');
$mary = new User('Mary');
echo $dave->getName(); // Dave
echo $mary->getName(); // Mary
User::hi(); // Hi
Unless you understand this, you know nothing about OOP.
First example is a non-static call to the method, second a static call.
The first is better if you want to access private variables of your Model, second is better if you use the method like a normal function.
In general you should declare methods of the first type as static (public static function method(){}).
First case is invocation of method on class instance, second case is call of static method.
See http://php.net/manual/en/language.oop5.static.php
There is no "proper" way because both call types serve different purposes.
The first call type is the standard way of handling objects: You initialize a concrete instance of a class. This instance can have its own internal values and each instance can use these values to create a different result when you call the method with the same parameter.
The second call type is called static and operates directly on the class, there is no instance (hence no $this). There are some use cases for it, see this answer for Java, it's the same for PHP.
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();