例如我在课堂上有这个:
private $messages = array(
'name'=> '<aa_f>name',
'PASS' => '<aa_p>'
);
但我想让<aa_p>
变成这样的变量:
private $pass = '<aa_p>';
我尝试了这4种方法,但都没有效果。 PHP.net没有这样做的例子。
'PASS' => $this->pass
'PASS' => $pass
'PASS' => '$this->pass'
'PASS' => '$pass'
完整代码
<?php
class Message
{
private $PASS = '<aa_p>';
private $FAIL = '<aa_f>';
private $messages = array(
'name'=> '<aa_f>name',
'email' => '<aa_f>email_s',
'pass' => '<aa_f>pass',
'url' => '<aa_f>url',
'title' => '<aa_f>title',
'tweet'=> '<aa_f>tweet',
'empty' => '<aa_f>empty',
'same' => '<aa_f>same',
'taken' => '<aa_f>taken',
'validate' => '<aa_f>validate',
'PASS' => '<aa_p>'
);
public function __construct()
{
}
public function display($type)
{
echo $this->messages[$type];
}
public function get($type)
{
return $this->messages[$type];
}
}
更新:回答
供参考:(更新代码)
class Message
{
private $PASS = '<aa_p';
private $FAIL = '<aa_f>';
private $messages = array();
public function __construct()
{
$this->messages['PASS'] = $this->PASS;
$this->messages['name'] = $this->FAIL . 'name';
$this->messages['email'] = $this->FAIL . 'email_s';
$this->messages['pass'] = $this->FAIL . 'pass';
$this->messages['url'] = $this->FAIL . 'url';
$this->messages['title'] = $this->FAIL . 'title';
$this->messages['tweet'] = $this->FAIL . 'tweet';
$this->messages['empty'] = $this->FAIL . 'empty';
$this->messages['same'] = $this->FAIL . 'same';
$this->messages['taken'] = $this->FAIL . 'taken';
$this->messages['validate'] = $this->FAIL . 'validate';
}
public function display($type)
{
echo $this->messages[$type];
}
public function get($type)
{
return $this->messages[$type];
}
}
答案 0 :(得分:2)
如果你的意思是你有这样的东西:
class Test {
private $pass = '<aa_p>';
private $messages = array(
'name' => '...',
'PASS' => '...'
);
}
并且您希望将'PASS'
设置为私有$pass
属性的值,然后您无法在定义中执行此操作,因为PHP语法不允许它。您必须在可以评估表达式的地方执行此操作,例如在方法中。构造函数将是一个很好的地方:
class Test {
private $pass = '<aa_p>';
private $messages = array(
'name' => '...'
);
public function __construct() {
$this->messages['PASS'] = $this->pass;
}
}
答案 1 :(得分:2)
您需要在构造函数中设置变量。在构造函数之外,您无法读取其他变量。
class Message{
private $PASS = '<aa_p>';
private $messages = array();
public function __construct(){
$this->messages['PASS'] = $this->PASS;
}
}
答案 2 :(得分:2)
只有在编译时可以确定的值才可用于启动类成员。您需要在运行时设置值(通过构造函数):
class Message
{
private $PASS = '<aa_p';
private $FAIL = '<aa_f>';
private $messages = array(
'name'=> '<aa_f>name',
'email' => '<aa_f>email_s',
'pass' => '<aa_f>pass',
'url' => '<aa_f>url',
'title' => '<aa_f>title',
'tweet'=> '<aa_f>tweet',
'empty' => '<aa_f>empty',
'same' => '<aa_f>same',
'taken' => '<aa_f>taken',
'validate' => '<aa_f>validate',
'PASS' => null
);
public function __construct()
{
$this->messages['PASS'] = $this->PASS;
}
}