如何从主范围内的子类中获取受保护的统计值 [英] How to get the protected stastic value from subclss in the main scope
本文介绍了如何从主范围内的子类中获取受保护的统计值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从子类获取值作为主作用域中受保护的 ststic 属性.我在这些行中使用,但不起作用.
How can i get the value frome child class as a protected ststic attribute in the main scope. I use in these lines but it doesn't work.
self::$table_name="Table_shape_B";
self::$table_name="Table_shape_C";
我想看看这些台词谢谢.
I want to see these lines Thanks.
selected Database Table name: Table_shape_B
selected Database Table name: Table_shape_C
输出是
new B : are created :
new C : are created :
selected Database Table name:
selected Database Table name:
这是我的代码:
<?php
abstract class Class_A {
protected static $table_name;
//Class_B Database Table name = "Table_shape_B"
//Class_CA Database Table name = "Table_shape_C"
public function __construct() {
echo "<br />"." new ".get_class($this)." : are created :";
}
public function get_table_name_protected() {
return self::$table_name;
}
}
class B extends Class_A {
//self::$table_name="Table_shape_B";
}
class C extends Class_A {
//self::$table_name="Table_shape_C";
}
$NewObject1= new B ( );
$NewObject2= new C ( );
echo "<br />".' selected Database Table name: '.$NewObject1->get_table_name_protected();
echo "<br />".' selected Database Table name: '.$NewObject2->get_table_name_protected();
?>
推荐答案
参见 http://docs.php.net/language.oop5.late-static-bindings
从 PHP 5.3.0 开始,PHP 实现了一个称为后期静态绑定的功能,可用于在静态继承的上下文中引用被调用的类.[...] 后期绑定"来自这样一个事实,即 static:: 不会使用定义方法的类来解析,而是使用运行时信息来计算.它也被称为静态绑定",因为它可以用于(但不限于)静态方法调用.
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. [...] "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
不幸的是,您不能像使用抽象成员方法那样强制"子类定义这个静态成员.
Unfortunately you can't "force" a subclass to define this static member like you can with abstract member methods.
<?php
abstract class Class_A {
public function __construct() {
echo get_class($this), "\n";
}
public function get_table_name_protected() {
return static::$table_name;
}
}
class B extends Class_A {
protected static $table_name="Table_shape_B";
}
class C extends Class_A {
protected static $table_name="Table_shape_C";
}
$NewObject1= new B ( );
$NewObject2= new C ( );
echo $NewObject1->get_table_name_protected(), "\n";
echo $NewObject2->get_table_name_protected(), "\n";
印刷品
B
C
Table_shape_B
Table_shape_C
这篇关于如何从主范围内的子类中获取受保护的统计值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文