将三个函数的输出组合在一个类中,然后显示最终输出



我试图理解类和函数是如何工作的。我正在尝试做一个示例,将两个不同的变量加在一起形成一个,然后输出它。

类中有 3 个函数 - 一个用于生成随机数,另一个用于生成随机单词,最后一个用于组合这两个函数的输出。

谁能指出我做错了什么?

<?php
class generateTicket
{
public function numbers()
{
$randomnum = number_format(random_int(1000, 9999) / 100, 2);
}

public function words()
{
$randomword = bin2hex(openssl_random_pseudo_bytes(8));
}
public function combined()
{
$A = $this->numbers($randomnum);
$B = $this->words($randomword);
echo $A . "-" . $B;
}
}
$class = new generateTicket();
$class->combined();
?>

您在组合方法中传递未知变量。 $randomnum和$randomword在以下行中未定义:

public function combined()
{
$A = $this->numbers($randomnum);
$B = $this->words($randomword);
echo $A . "-" . $B;
}

您在这里有几个选择:

一种选择是返回变量:

public function numbers()
{
return number_format(random_int(1000, 9999) / 100, 2);
}

public function words()
{
return bin2hex(openssl_random_pseudo_bytes(8));
}
public function combined()
{
$A = $this->numbers();
$B = $this->words();
echo $A . "-" . $B;
}

另一种选择如下:

public function numbers()
{
$this->randomnum = number_format(random_int(1000, 9999) / 100, 2);
}

public function words()
{
$this->randomword = bin2hex(openssl_random_pseudo_bytes(8));
}
public function combined()
{
$this->numbers();
$this->words();
echo $this->randomnum . "-" . $this->randomword;
}

最新更新