[英]How do I call a static child function from parent static function?
如何从父 static function 调用子 function?
在 php5.3 中有一个名为get_called_class()
的内置方法可以从父 class 调用子方法。 但是我的服务器正在运行php 5.1 。
有什么办法可以做到这一点?
我想从 static function 调用它。 这样我就不能使用“$this”
所以我应该使用“self”关键字。
Below example my parent class is "Test123", from the parent class static function "myfunc" am trying to call child class function like this "self::test();"
abstract class Test123
{
function __construct()
{
// some code here
}
public static function myfunc()
{
self::test();
}
abstract function test();
}
class Test123456 extends Test123
{
function __construct()
{
parent::__construct();
}
function test()
{
echo "So you managed to call me !!";
}
}
$fish = new Test123456();
$fish->test();
$fish->myfunc();
编辑: PHP 5.1 无法实现您尝试实现的目标。 There is no late static bindings PHP Manual in PHP 5.1, you need to explicitly name the child class to call the child function: Test123456::test()
, self
will be Test123
in a static function of the class Test123
(always) and the static
关键字不可用于调用 Z2FEC392304A5723AC138F14Z 中的 static function。
相关:新自我与新 static ; PHP 5.2 相当于后期Static绑定(新静态)?
If you are referring to a static parent function, then you need to explicitly name the parent (or child) for the function call in php 5.1:
parentClass::func();
Test123456::test();
在 PHP 5.3 中,您可以使用static
关键字PHP 手动解析被调用类的名称:
static::func();
static::test();
如果这些是非静态的,只需使用$this
PHP 手册:
$this->parentFunc();
$this->childFunc();
或者如果它具有相同的名称,请使用parent
PHP 手册:
parent::parentFunc();
(这不完全是您所要求的,只是为了完整起见将其放在这里)。
Get_called_class() 已针对非常具体的情况引入,例如后期 static 绑定PHP 手册。
我怀疑您对父/子 class / object 和 function / 方法有点困惑。
Ionuț G. Stan 解释了如何调用未在父 class 中声明的方法(正如他所说,这应该是抽象的或实现 __call() 方法)。
但是,如果您的意思是如何从父级调用已在子级 class 中被覆盖的方法,那么这是不可能的 - 也不应该是。 考虑:
Class shape {
...
}
Class circle extends shape {
function area() {
}
}
Class square extends shape {
function area() {
}
}
如果您打算在“shape”实例(没有 area 方法)上调用 area 方法,那么它应该使用哪个子节点? 这两种子方法都将取决于不常见/未由形状 class 实现的属性。
尝试这个:
<?php
class A {
public static function newInstance() {
$rv = new static();
return $rv;
}
public function __construct() { echo " A::__construct\n"; }
}
class B extends A {
public function __construct() { echo " B::__construct\n"; }
}
class C extends B {
public function __construct() { echo " C::__construct\n"; }
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.