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.
Related
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
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
See the class definition below:
I am currently using 5.3.9 version of PHP
class A{
static function ab(){
echo "static function ab<br>";
}
public function xy(){
echo "public function xy<br>";
}
}
$obj = new A();
$obj->ab();
A::ab();
Both functions call give the same output without any error
static function ab
static function ab
How it is possible that static method can also be called by class object?
Because static method only calls by using class name only?!
Now what is the difference between accessing these two ways to call static method?
Referring to php.net website
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
A big difference is
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.
Refer to the page php.net/manual/en/language.oop5.static.php for more details
As long as you are just echoing a simple string, there's no difference, if your method will be declared static or public, since static method can also be called with the object instance. As of PHP 5.5 an error will raise if you call your public method with a static way. However, the static method can be called with classname::staticMethod() so the page should only know about the class, but not really needs an instance of it.
The other deal is the method content. As I said, if you just echo a string, you don't need a static method for that. A static method is out of the object context. That means you cannot access properties or methods from the current object via $this
I am really going crazy with this problem.
I am not able to call a method from the parent class in a static method of a child class..
This is what I tried but it does not work..
class custom extends service {
private $service;
function __construct() {
parent::__construct();
$this->service = new service;
}
public static function activematches($callback) {
$select_by_user = parent::$db->select('matches', '*', array('user_id' => $user_id,
if (count($select_by_user) == 0 && count($select_by_opponent) == 0)
parent::$check->send('11');
else
$this->service->make($callback['request'], $callback['data']);
}
When I call $this->service I get:
Fatal error: Using $this when not in object context
I tried making that as static, I tried putting the same method in the child class by calling the parent method parent::method, but nothing...
I am new to OOP, any help?
For access within a static invocation the property must be defined static as well
protected static $services;
From there you need to reference within your static methos as either.
self::$services
or
static::$services
Referencing self in this context will refer to $services property where the reference is defined. static will reference the property from the class context that the reference was invoked on. For more information see what the manual has to say about late static binding
UPDATE
Based on the fact that custom extends service in this case I doubt this is what you are really after. A class definition like :
class custom extends service {
public function activematches($callback, $user_id) {
$select_by_user = $this->db->select('matches', '*', array('user_id' => $user_id));
if (count($select_by_user) == 0 && count($select_by_opponent) == 0)
$this->check->send('11');
else
$this->make($callback['request'], $callback['data']);
}
}
May be closer to what you want.
If the parent method, make is not static:
You can't call a non-static method from the parent class from a static method of the child class. Have you considered making the child method not-static? I think that's your best option here.
If the parent method make is static:
parent::make($callback['request'], $callback['data']);
But this is called Late Static Bindings which was introduced in PHP 5.3.0. It won't work in older versions, so be careful with that.
Fatal error: Using $this when not in object context
This is actually answer for your question. The specific of static members of class is - you can use them without making an object. $this - reference for object, in which context method was called.
So try to look on problem in this way - in static member you don't have any $this.
You can only use static members of parent class in this way - self::method.
Or, you can actually create an object on parent class and use any "dynamic" method in "dynamic" notation, but this will make you even more crazy later, believe me)
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