I would like to know if it is acceptable/preferred to use self::method() and parent::method() when working in php classes.
You can use $this->method() but $this-> can al
Controllers are not static in Kohana, although they can contain static member variables / methods or constants.
self::
is a shorthand way of writing ClassName::
i.e
class Animal
{
public static $arms = 0;
}
class Dog extends Animal
{
public static $leg = 0;
const NAME = 'dog';
public static function bark()
{
echo 'Woof';
}
}
To call static functions or get constants from a class we use the scope resolution operator ::
. Static functions are per class not per object. Saying ::
refers to static instances of a class is wrong, it is just a way to access the static methods - there isn't an object instance that has these methods.
so:
Dog::bark(),
Dog::$leg,
Dog::NAME,
we can also use
Animal::$arms
Inside the class Dog we can use self::
and parent::
so that we do not need to type the full class name (as it could be very long!)
In answer to your question though: No - self::
is not deprecated and no it is not bad practice to use it. The reason it is not used in kohana core is for a very different reason.... (transparent class extensions with eval
read below for more info...).
p.s calling non-static methods statically is wrong and shouldn't be allowed- if you set error_reporting(E_ALL | E_STRICT)
(like you should during development) you will see an error being raised.
Basically what happens is:
Core has a file called:
class Controller_Core {
public function someMethod(){}
}
You create:
// We can use someMethod of Controller_Core
Index_Controller extends Controller {}
This is really extending Controller_Core
UNLESS you have created MY_Controller.php which would be class Controller extends Controller_Core
.
//MY_Controller.php
class Controller extends Controller_Core
{
// overloads Controller_Core::someMethod without us having to change the core file
public function someMethod(){}
}