我该如何让一个PHP类在其构造函数中实例化另一个类?
我很新,在这里和PHP。我该如何让一个PHP类在其构造函数中实例化另一个类?
我想知道在他的参数中在另一个类构造函数中实例化类的正确方法。
(我在钮一些狗屎测试)
class CryptoControl { public $helper;
public $keyValues;
public function __construct ($primo1, $primo2, $message) {
$this->helper = new MathHelper();
$this->keyValues = new KeyValues($primo1, $primo2, $message);
}
public function criptografa_descriptografa_simetrica() {
$message = $keyValues->getMessage();
echo "Texto original: " . $message . "\n";
echo "Chave criptografada: " . base64_encode($message) . "\n";
$message_criptografada = base64_encode($message);
echo "Chave descriptografada: " . base64_decode($message_criptografada) . "\n";
}
}
$exec = new CryptoControl(17, 41, "TURING");
$resposta = $exec->criptografa_descriptografa_simetrica();
echo $resposta;
而这是我想将类实例:
class KeyValues { public $numeroPrimo_1;
public $numeroPrimo_2;
public $message;
public function KeyValues ($primo1, $primo2, $message) {
$this->numeroPrimo_1 = $primo1;
$this->numeroPrimo_2 = $primo2;
$this->message = $message;
}
#getters and setters
}
这是我得到的错误..
PHP注意:未定义的变量:keyValues在/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php上线72 PHP致命错误:调用成员函数getM essage()非对象/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php在线72
感谢您的帮助......
回答:
更改以下行
$message = $keyValues->getMessage();
到
$message = $this->keyValues->getMessage();
$keyValues
在一个类里面的方法引用一个局部变量。当您使用$this
关键字进行访问时,它将引用该类的对象的属性。
回答:
class KeyValues { public $numeroPrimo_1;
public $numeroPrimo_2;
public $message;
public function KeyValues ($primo1, $primo2, $message) {
$this->numeroPrimo_1 = $primo1;
$this->numeroPrimo_2 = $primo2;
$this->message = $message;
}
public function getMessage() {
return $this->message;
}
#getters and setters
}
class CryptoControl {
public $helper;
public $keyValues;
public function __construct ($primo1, $primo2, $message) {
$this->helper = new MathHelper();
$this->keyValues = new KeyValues($primo1, $primo2, $message);
}
public function criptografa_descriptografa_simetrica() {
$message = $this->keyValues->getMessage();
echo "Texto original: " . $message . "\n";
echo "Chave criptografada: " . base64_encode($message) . "\n";
$message_criptografada = base64_encode($message);
echo "Chave descriptografada: " . base64_decode($message_criptografada) . "\n";
}
}
$exec = new CryptoControl(17, 41, "TURING");
$resposta = $exec->criptografa_descriptografa_simetrica();
echo $resposta;
以上是 我该如何让一个PHP类在其构造函数中实例化另一个类? 的全部内容, 来源链接: utcz.com/qa/257378.html