我有以下php代码:
with open(path_in + data_file) as csvfile:
read_it = list(csv.reader(csvfile, delimiter=','))
结果是
<?php
class ParentClass {
public $table_name;
function __construct() {
$this->table_name = strtolower(__CLASS__);
}
}
class ChildClass extends ParentClass {
function __construct() {
parent::__construct();
//And I also want to put here other codes
}
}
$parent = new ParentClass();
$child = new ChildClass();
echo $parent->table_name . "<br />" . $child->table_name;
?>
然而我希望它是
parentclass
parentclass
我如何实现它? 后期静态绑定可以解决我的问题,但当然不能静态调用。 http://php.net/manual/en/language.oop5.late-static-bindings.php
答案 0 :(得分:3)
这适用于PHP5.5及更高版本:
class ParentClass
{
public $table_name;
public function __construct()
{
$this->table_name = strtolower(static::class);
}
}
class ChildClass extends ParentClass
{
public function __construct()
{
parent::__construct();
// ...
}
}
$parent = new ParentClass();
$child = new ChildClass();
echo $parent->table_name . "<br />" . $child->table_name;
供参考,请参阅http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class。
答案 1 :(得分:1)
使用static::class
使用后期静态绑定获取类的名称:
class ParentClass {
public $table_name;
function __construct() {
$this->table_name = strtolower(static::class);
}
}
这将产生所需的
parentclass
childclass
答案 2 :(得分:0)
<?php
class ParentClass {
public $table_name;
function __construct() {
$this->table_name = strtolower(__CLASS__);
}
}
class ChildClass extends ParentClass {
function __construct() {
parent::__construct();
$this->table_name = strtolower(__CLASS__);
//And I also want to put here other codes
}
}
$ parent = new ParentClass(); $ child = new ChildClass();
echo $ parent-&gt; table_name。 &#34;
&#34; 。 $儿童安全&GT;表名;
&GT;