本文介绍了如何从主范围内的子类中获取受保护的统计值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从子类获取值作为主作用域中受保护的 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
不幸的是,您不能像使用抽象成员方法那样强制"子类定义这个静态成员.
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
这篇关于如何从主范围内的子类中获取受保护的统计值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!