static class inheritant not work in PHP? - php

abstract class base {
abstract public function test();
public function run()
{
self::test();
}
}
class son extends base {
public function test()
{
echo 1;
}
}
son::run();
It reports:
Fatal error: Cannot call abstract
method base::test()
But son::test() works,why and is there a way to fix?

"self" is lexically scoped, that is, if you use "self" in a method of Base, "self" means "Base", no matter how you call this method at run time. php5.3 introduced a new kind of dynamic binding, which, ironically enough, is called "static". The following works as expected in php 5.3
abstract class base {
abstract public static function test();
static public function run()
{
static::test();
}
}
class son extends base {
static public function test()
{
echo 1;
}
}
son::run();

Of course:
Fatal error: Cannot call abstract method base::test()
It has no method body you could call. If run() is supposed to be a Template Method, you refer to the class scope with $this instead of self and then create an instance of $son to call run() on it, e.g.
abstract class BaseClass {
abstract public function test();
public function run()
{
$this->test();
}
}
class Son extends BaseClass {
public function test()
{
echo 1;
}
}
$son = new Son;
$son->run(); // 1
which is rather odd, because then you could have just as well called test() directly.
Also note that in your example
son::run();
is wrong, because the run() method is not declared static and while PHP will execute run() nonetheless, it is considered wrong usage and will raise an E_STRICT error. However, if you were to define run() static, you could no longer reference $this, because a static method is not invoked from instance scope, but class scope.
Edit I was about to add the PHP5.3 solution, but see that #erenon already did that, while I was typing, so I only add the appropriate reference in the PHP Manual on Late Static Binding.

Abstract methods do not have an implementation, and thus cannot be called. If the method is not defined as abstract, and actually has an implementation, then it can be executed by your code. For example:
public function test(){
echo "Hello from base!";
}

Factory/singleton pattern mix:
class Base
{
static private $instance;
static function getSon() {
if (null === self::$instance) {
self::$instance = new Son;();
}
return self::$instance;
}
}
class Son
{
public function test() {
echo 1;
}
}
Base::getSon()->test(); //1

Related

PHP inheritance of reflection methods [duplicate]

I have two classes: Action and MyAction. The latter is declared as:
class MyAction extends Action {/* some methods here */}
All I need is method in the Action class (only in it, because there will be a lot of inherited classes, and I don’t want to implement this method in all of them), which will return classname from a static call. Here is what I’m talking about:
Class Action {
function n(){/* something */}
}
And when I call it:
MyAction::n(); // it should return "MyAction"
But each declaration in the parent class has access only to the parent class __CLASS__ variable, which has the value “Action”.
Is there any possible way to do this?
__CLASS__ always returns the name of the class in which it was used, so it's not much help with a static method. If the method wasn't static you could simply use get_class($this). e.g.
class Action {
public function n(){
echo get_class($this);
}
}
class MyAction extends Action {
}
$foo=new MyAction;
$foo->n(); //displays 'MyAction'
Late static bindings, available in PHP 5.3+
Now that PHP 5.3 is released, you can use late static bindings, which let you resolve the target class for a static method call at runtime rather than when it is defined.
While the feature does not introduce a new magic constant to tell you the classname you were called through, it does provide a new function, get_called_class() which can tell you the name of the class a static method was called in. Here's an example:
Class Action {
public static function n() {
return get_called_class();
}
}
class MyAction extends Action {
}
echo MyAction::n(); //displays MyAction
Since 5.5 you can use class keyword for the class name resolution, which would be a lot faster than making function calls. Also works with interfaces.
// C extends B extends A
static::class // MyNamespace\ClassC when run in A
self::class // MyNamespace\ClassA when run in A
parent::class // MyNamespace\ClassB when run in C
MyClass::class // MyNamespace\MyClass
It's not the ideal solution, but it works on PHP < 5.3.0.
The code was copied from septuro.com
if(!function_exists('get_called_class')) {
class class_tools {
static $i = 0;
static $fl = null;
static function get_called_class() {
$bt = debug_backtrace();
if (self::$fl == $bt[2]['file'].$bt[2]['line']) {
self::$i++;
} else {
self::$i = 0;
self::$fl = $bt[2]['file'].$bt[2]['line'];
}
$lines = file($bt[2]['file']);
preg_match_all('/([a-zA-Z0-9\_]+)::'.$bt[2]['function'].'/',
$lines[$bt[2]['line']-1],
$matches);
return $matches[1][self::$i];
}
}
function get_called_class() {
return class_tools::get_called_class();
}
}
Now (when 5.3 has arrived) it's pretty simple:
http://php.net/manual/en/function.get-called-class.php
class MainSingleton {
private static $instances = array();
private static function get_called_class() {
$t = debug_backtrace();
return $t[count($t)-1]["class"];
}
public static function getInstance() {
$class = self::get_called_class();
if(!isset(self::$instances[$class]) ) {
self::$instances[$class] = new $class;
}
return self::$instances[$class];
}
}
class Singleton extends MainSingleton {
public static function getInstance()
{
return parent::getInstance();
}
protected function __construct() {
echo "A". PHP_EOL;
}
protected function __clone() {}
public function test() {
echo " * test called * ";
}
}
Singleton::getInstance()->test();
Singleton::getInstance()->test();
(PHP 5 >= 5.3.0, PHP 7)
get_called_class — The "Late Static Binding" class name
<?php
class Model
{
public static function find()
{
return get_called_class();
}
}
class User extends Model
{
}
echo User::find();
this link might be helpfull
There is no way, in the available PHP versions, to do what you want. Paul Dixon's solution is the only one. I mean, the code example, as the late static bindings feature he's talking about is available as of PHP 5.3, which is in beta.

How to call a non static method using static keyword?

I am just checking the OOPs static/non-static concept and found something strange.
I have heard that static method's output can be get by using static keyword with resolution operator(::) . But In my program I am getting non static method's value using static keyword. Can any one explain the program? I am getting confused.
<?php
error_reporting(E_ALL);
class parentclass
{
protected function sum()
{
return 145;
}
}
class childclass extends parentclass
{
protected function sum()
{
return 125;
}
}
class grandchild extends childclass
{
function sum()
{
return 100;
}
function __construct()
{
echo static::sum(); // 100 as output but how
}
}
$obj = new grandchild();
?>
Besides this If I am making function sum() of childclass as static like
class childclass extends parentclass
{
protected static function sum()
{
return 125;
}
}
then also it is giving fatal error as following:
Fatal error: Cannot make non static method parentclass::sum() static in class childclass
But why I am not calling that function.
You can call a function statically, even if it is not declared as static, as long as you don't reference $this inside it.
That is why the original code works.
You cannot, however, change the signature of an inherited method.
Fatal error: Cannot make non static method parentclass::sum() static
in class childclass
When you declare protected static function sum() in childclass, you are changing the signature of the inherited method from parentclass which is not specifically declared static.
Bottomline, you are trying to use some PHP quirks that I would recommend against. Yes, they work, but that doesn't mean you should use them.
Stick to a strict style of coding. Write separate methods for static and instance use and call them as intended.
You are using static as a Late Static Binding. But what you heard about was rather
class Foo
{
static function bar() {}
}
$baz = Foo::bar();
I think to understand late static bindings a bit better you could write a variation of your code:
<?php
error_reporting(E_ALL);
class parentclass
{
protected function sum()
{
return 145;
}
public function do_the_math()
{
printf('Static sum: %d, Self sum: %d',
static::sum(),
self::sum());
}
}
class childclass extends parentclass
{
protected function sum()
{
return 125;
}
}
class grandchild extends childclass
{
function sum()
{
return 100;
}
}
$obj = new grandchild();
$obj->do_the_math();
Output:
Static sum: 100, Self sum: 145

Abstract trait't method not allowed to be static in PHP?

Here is my example:
trait FileConfig {
public static function getPathForUploads() {
$paths = static::getPaths();
//etc.
}
abstract public static function getPaths(); //doesn't work. Error: "Static function SharedDefaultConfig::getPaths() should not be abstract"
abstract public function getPaths(); //OK
public static function getPaths() {} //OK
}
Class:
class AppConfig {
use FileConfig;
public static function getPaths() {
return array(...);
}
}
Call:
AppConfig::getPathForUploads();
It's nessessary to make it static and abstract (to force classes using FileConfig to implement getPaths).
I wonder how is it possible to implement method changing it's static property? Is it a good practice or there are better solutions? Will it one day become illegal?
Thank you
This is fixed in php 7, so the following code works:
<?php
error_reporting(-1);
trait FileConfig {
public static function getPathForUploads() {
echo static::getPaths();
}
abstract static function getPaths();
}
class AppConfig {
use FileConfig;
protected static function getPaths() {
return "hello world";
}
}
AppConfig::getPathForUploads();
http://sandbox.onlinephpfunctions.com/code/610f3140b056f3c3e8defb84e6b57ae61fbafbc9
But it does not actually check if the method in AppConfig is static or not during compilation. You will only get a warning when you try to call the non-static method statically: http://sandbox.onlinephpfunctions.com/code/1252f81af34f71e901994af2531104d70024a685
You do not need to make the method static to force classes using it to implement the method. You can simply use interfaces alongside.
trait FileUploadConfig {
public static function getPathForUploads() {
$paths = static::getPaths();
//etc.
}
}
The trait was left as is. I just took away the functions for the interface.
interface PathConfiguration {
public static function getPaths();
}
The interface forces the class to implement the function. I left the static in there to correspond with the trait's specification.
class AppConfig implements PathConfiguration {
use FileUploadConfig;
public static function getPaths() {
return [];
}
}
To force classes using FileConfig to implement getPaths it's not nessessary to make abstract function static. Static means that it belongs to the class that declared it. Make it protected static, add code from trait and then you could change behaviour by inheritance from your AppConfig class.

php scope resolution operator

Why does this return a "strict standard" notice?:
'Strict Standards: Non-static method main::i() should not be called statically in...'
class main
{
public function __construct()
{
echo "in main class";
}
public function i()
{
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
I am legally calling a static method which contains a call to a non static method in a parent class.
The notice is telling you should not call a non static method within a static method.
You could check the method i(), if $this doesn't appear in that method, you may consider change i() to static method.
You've already answered the question yourself - while you're calling tom() statically (which is fine), i() is not static.
Being non-static i() assumes that you have an instance of the object, and therefore could be trying to access properties or perform other actions which require an instance. As such it shouldn't be called statically, not even from within a static method in a child class. Consider for example the following slight change to your code:
class main
{
var something = 0;
public function __construct()
{
echo "in main class";
}
public function i()
{
$this->something++;
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
It's a strict warning - meaning you can choose to ignore it if you want to - but it's informing you that what you're doing is not generally good practice and you should probably rethink your approach.
class main
{
public function __construct()
{
echo "in main class";
}
public static function i()
{
echo "i in main";
}
}
class secondary extends main
{
public static function tom()
{
parent::i();
}
}
secondary::tom();
Is what it should look like, notice I have converted the function i(); to a static, which then can legally be called by parent::i();
But performing:
public static function tom()
{
$this->i();
}
Will return:
Fatal error: Using $this when not in object context
So your bet is to go fully static, or not static.
A resolution:
class main
{
public function __construct()
{
echo "in main class";
}
public function i()
{
echo "i in main";
}
}
class secondary extends main
{
public function tom()
{
$this->i();
}
}
$Class = new secondary();
$Class->tom();

Access parent properties in child using $this

I am trying to create a simple MVC my personal use and I could really use an answer to this simple question
class theParent extends grandParent{
protected $hello = "Hello World";
public function __construct() {
parent::__construct();
}
public function route_to($where) {
call_user_func(array("Child", $where), $this);
}
}
class Child extends theParent {
public function __construct() {
parent::__construct();
}
public function index($var) {
echo $this->hello;
}
}
$x = new theParent();
$x->route_to('index');
Now Child::index() this throws a fatal error: Using $this when not in object context but if I were to use echo $var->hello, it works just fine.
I know I can use $var to access all properties in the parent, but I would rather use $this.
By writing call_user_func(array("Child", $where), $this) you are calling the method statically. But as your method isn't static you need some kind of object instance:
call_user_func(array(new Child, $where), $this);
Documentation on callback functions.
You don't have an instance of Child to call a non-static method upon when you're doing $x->route_to('index'); The way you're calling the method, without having made an instance first, is implied static.
There are two ways to correct it. Either make the Child class's methods static:
class Child extends theParent {
public function __construct() {
parent::__construct();
}
static public function index($var) {
echo self::$hello;
}
}
...or make an instance of the child class for the parent to use:
class theParent extends grandParent{
protected $hello = "Hello World";
private $child = false
public function __construct() {
parent::__construct();
}
public function route_to($where) {
if ($this->child == false)
$this->child = new Child();
call_user_func(array($this->child, $where), $this);
}
}
Of course, both of these samples are rather generic and useless, but you see the concept at hand.
$this gives you access to everything visible/accessible in the current object. That can either be in the class itself (this) or any of it's parents public or protected members/functions.
In case the current class overrides something of a parent class, you can access the parent method explicitly using the parent keyword/label, whereas you add :: to it regardless if it is not a static method.
Protected variables exist only once, so you can not use parent to access them.
Is this info of use?

Categories