1 回答

TA貢獻1772條經驗 獲得超5個贊
當你實例化變量時,它們有一定的范圍,在這個范圍內變量是已知的。我不明白你是如何加載文件的,但我假設你希望在訪問 index.php 時發生 transaction.php 的邏輯。要實現此目的,可以將 transaction.php 放入一個以 $errors 作為構造函數變量的類,實例化它并調用該方法:
[交易.php]
class Transaction
{
? ? private $errors;
? ? public function _construct($errors)
? ? {
? ? ? ? ?$this->errors = $errors;
? ? }
? ? public function handleErrors()
? ? {
? ? ? ? if(is_array($errors))
? ? ? ? {
? ? ? ? ? ? echo 'something';
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? echo 'something';
? ? ? ? }
? ? }
}
[getTransaction.php]
Class Template
{
? ? public function __construct($template, $vars)
? ? {
? ? ? ? $this->template = $template;
? ? ? ? $this->vars = $vars;
? ? ? ? $transaction = new Transaction($vars); //instantiates your class
? ? ? ? $transaction->handleErrors(); //calls the method
? ? }
? ? public function __toString()
? ? {
? ? ? ? foreach ($this->vars as $name => $value)
? ? ? ? {
? ? ? ? ? ? $name = $value;
? ? ? ? }
? ? ? ? unset($name, $value);
? ? ? ? ob_start();
? ? ? ? require('templates/' . $this->template . '.php');
? ? ? ? return ob_get_clean();
? ? }
}
或者將 transaction.php 變成您在 index.php 中定義并調用的函數: [index.php]
function checkTransaction()
{
? ? if(!empty($_POST['code']))
? ? {
? ? ? ? return true;
? ? }
? ? return [
? ? ? ? 'code' => false
? ? ];
}
function handleErrors($errors)
{
? ? if(is_array($errors))
? ? {
? ? ? ? echo 'something';
? ? }
? ? else
? ? {
? ? ? ? echo 'something';
? ? }
}
function renderTransactionResult($errors)
{
? ? $getTemplate = new Template('transaction', [
? ? ? ? 'errors' => $errors
? ? ]);
? ? echo $getTemplate;
}
$transactionid = htmlspecialchars($_POST['search']);
$transactionrows = $main->CheckNumRowsTransaction($transactionid);
if($transactionrows === 1)
{
? ? $errors = checkTransaction($_POST);
? ? renderTransactionResult($errors);
}
else
{
? ? $errors = [
? ? ? ? 'transaction' => false
? ? ];
? ? renderTransactionResult($errors);
}
請注意,我沒有審查您的功能、效率或安全性代碼,而只是制定了解決您的范圍問題的答案。
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報