我非常喜欢这里和PHP。
我想知道在他的参数中用另一个类构造函数实例化一个类的正确方法。
(我在botton中有一些狗屎测试)
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注意:未定义的变量:第72行/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php中的keyValues PHP致命错误:在第72行的/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php中的非对象上调用成员函数getMessage()
感谢您的帮助......
答案 0 :(得分:4)
更改以下行
$message = $keyValues->getMessage();
到
$message = $this->keyValues->getMessage();
类中的方法内的 $keyValues
引用局部变量。当您使用$this
关键字进行访问时,它会引用该类对象的属性。
答案 1 :(得分:0)
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;