Friday, July 22, 2022

[FIXED] How to use class_exists correctly in PHP 5.4

Issue

I'm using an old system with PHP 5.4 that I can't upgrade. I had to make a small change by adding a library for PDF file generation called FPDF/FPDI that has this function:

protected function getPdfParserInstance(StreamReader $streamReader)
{
    /** @noinspection PhpUndefinedClassInspection */
    if (\class_exists(FpdiPdfParser::class)) {
        /** @noinspection PhpUndefinedClassInspection */
        return new FpdiPdfParser($streamReader);
    }

    return new PdfParser($streamReader);
}

The problem is that ::class was added in PHP 5.5 as explained in this question.

The question is: what changes need to be made to this function to work in PHP 5.4?


Solution

::class just evaluates to the string containing the class' full name, so use that instead. Looking at the top of the file for the use statements, you'll find that FpdiPdfParser is just an alias, so your code should be rewritten to look like this:

if (class_exists("setasign\\FpdiPdfParser\\PdfParser\\PdfParser"))

You don't, strictly speaking, need to escape the backslashes; few escape sequences contain capital letters, but it's good practice to do so anyway.

It's unlikely this will be the only compatibility issues you'll come across. If a system can run PHP 5.4, it can almost certainly run PHP 5.6 which is only a couple of years out of date.



Answered By - miken32
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.