这是我的PHP示例代码,我想动态访问另一个类的静态属性,基本上我有一个存储在变量中的类名。
# Main Class
class HelloAction
{
const FIRST = "DEMO";
public static $first = "WORLD";
function __construct($confclassname)
{
$this->config = $confclassname;
# PHP Interpreter throws an Error for These Two Lines
$this->first1 = $this->config::$a;
$this->first2 = $this->config::$b;
}
function setFirst($s)
{
self::$first = $s;
}
}
# Configuration Class
# Can hold only static or constants values
class action1
{
const AAAA = "____Hello World____";
public static $a = "this is an apple";
public static $b = "That is an Dog";
function __construct()
{
$this->second = "hi, there.";
}
}
# Configuration Class
# Can hold only static or constants values
class action2
{
const AAAA = "___Yeah, Hello World____";
public static $a = "Whare You were...";
public static $b = "Awesome work";
function __construct()
{
}
public static function action21($s)
{
self::$a = $s;
}
public function action22()
{
return self::$a;
}
}
# We want to inject configuration Object into Main Class Object
$b1 = new HelloAction('action1');
$b2 = new HelloAction('action2');
echo $b1->first1 . "\n";
echo $b1->first2 . "\n";
错误:解析错误:语法错误,第11行的F:\ xampp \ htdocs \ 6-project-n_demos \ 011.php中出现意外的'::'(T_PAAMAYIM_NEKUDOTAYIM)
注释行11
,12
然后尝试执行操作var_dump
this->config
,您将看到它不是在选择整个对象,而是__construct
因为您是在对象上调用静态方法,因此请尝试以下代码
class HelloAction
{
const FIRST = "DEMO";
public static $first = "WORLD";
function __construct($confclassname)
{
$this->config = $confclassname;
# PHP Interpreter throws an Error for These Two Lines
$this->first1 = $confclassname::$a;
$this->first2 = $confclassname::$b;
}
function setFirst($s)
{
self::$first = $s;
}
}
class action1
{
const AAAA = "____Hello World____";
public static $a = "this is an apple";
public static $b = "That is an Dog";
function __construct()
{
$this->second = "hi, there.";
}
}
class action2
{
const AAAA = "___Yeah, Hello World____";
public static $a = "Whare You were...";
public static $b = "Awesome work";
function __construct()
{
}
public static function action21($s)
{
self::$a = $s;
}
public function action22()
{
return self::$a;
}
}
$b1 = new HelloAction('action1');
$b2 = new HelloAction('action2');
echo $b1->first1 . "\n";
echo $b1->first2 . "\n";
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句