首页 > 解决方案 > 函数选项中的 PHP 变量

问题描述

我想使用以下 FPDF 扩展名对某些 PDF 进行密码保护

function SetProtection($permissions=array(), $user_pass='ABC123', $owner_pass='ABC123!')

但是我希望 $user_pass 是上面定义的变量,例如出生日期。到目前为止我尝试过的选项包括

function SetProtection($permissions=array(), $user_pass=''.$dateofbirth, $owner_pass='ABC123!')
function SetProtection($permissions=array(), $user_pass=$dateofbirth, $owner_pass='ABC123!')
function SetProtection($permissions=array(), $user_pass='".$dateofbirth."', $owner_pass='ABC123!')

但是我通常会遇到同样的问题,密码基本上是“”中任何内容的纯文本,而不是变量,例如,在最后一种情况下,密码的".$dateofbirth."输入方式与此完全相同。

我正在努力寻找正确的语法。

谢谢

亨利

标签: javascriptphparraysoptions

解决方案


您不能将变量用作默认值。要达到相同效果,您可以做的最接近的事情是手动检查和替换参数变量,例如,

function SetProtection($permissions=array(), $user_pass=null, $owner_pass='ABC123!')
{
    // You can also check if empty string if you have a use-case where empty string
    // would also mean replace with $dateofbirth
    if ($user_pass === null) {
        global $dateofbirth;
        $user_pass = $dateofbirth;
    }

    ...
}
$SetProtection = function ($permissions=array(), $user_pass=null, $owner_pass='ABC123!') use ($dateofbirth)
{
    // You can also check if empty string if you have a use-case where empty string
    // would also mean replace with $dateofbirth
    if ($user_pass === null) {
        $user_pass = $dateofbirth;
    }

    ...
}
class SomeClass()
{
    private $dateofbirth;

    ...

    function SetProtection($permissions=array(), $user_pass=null, $owner_pass='ABC123!')
    {
        // You can also check if empty string if you have a use-case where empty string
        // would also mean replace with $dateofbirth
        if ($user_pass === null) {
            $user_pass = $this->dateofbirth;
        }

        ...
    }

推荐阅读