Skip to content
Advertisement

PHP Variable in function options

I want to use the following FPDF extension to password protect some PDFs

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

However I want the $user_pass to be a variable definded above, such as date of birth. The options I have tried so far include

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!')

however i’m usually met with the same issue where the password is basically the plain text of anything in the ” and not the variabe, in that final case for example, the password is ".$dateofbirth." entered exactly like that.

I’m struggling to find the correct syntax.

Thanks

Henry

Advertisement

Answer

You can not use variables as default values. The closest thing you can do to achieve the same effect is to manually check and replace the argument variable, eg,

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;
        }

        ...
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement