使用变量进入php公共php函数

时间:2015-05-24 23:04:17

标签: php function class public

我是php的新手。我有:

require_once('tcpdf_include.php');

    $poruka = $user['porukanadnu'];

class MYPDF extends TCPDF {


    // Page footer
    public function Footer() {

        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$poruka, 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

为什么我不能将变量$poruka用于公共函数?以及如何使它成为可能?

1 个答案:

答案 0 :(得分:1)

您正在尝试在类中使用$poruka,但它超出了范围,如果您首先将其声明为全局范围,则可以在类中使用它,例如:

require_once('tcpdf_include.php');

$poruka = $user['porukanadnu'];

class MYPDF extends TCPDF {


    // Page footer
    public function Footer() {
        global $poruka;     // This will let you use $poruka.

        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$poruka, 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

或者你可以将它传递给函数,如下所示:

require_once('tcpdf_include.php');

$poruka = $user['porukanadnu'];

class MYPDF extends TCPDF {


    // Page footer
    public function Footer($poruka) {

        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$poruka, 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

但是当你调用该函数时,你必须将它作为一个属性包含在内:

   Footer($poruka);