Home > Enterprise >  PHP 8.1 var is declared in class and value to this var assigned in function but value is not availab
PHP 8.1 var is declared in class and value to this var assigned in function but value is not availab

Time:08-29

I'm trying to implement a contact form for a website running on PHP 8.1 and found some useful PHP scripts which seem to be outdated by now, though. I've refactored it as best as I can but I still get an error saying "imagecreate(): Argument #1 ($width) must be greater than 0". Here is the code

class FGCaptchaCreator extends FG_CaptchaHandler
{
    var $image;
    var $width;
    var $height;
    var $margin_y;
    var $charset;
    var $nChars;
    var $linecolor;
    var $code;
    var $show_captcha_var;
    var $nlines;
    var $enc_key;
    var $captcha_var_name;

    function FGCaptchaCreator($captcha_var_name)
    {
        $this->width = 150;
        $this->height= 60;
        $this->charset="2356789ABCDEFGHJKLMNPQRSTUVWXYZ";
        $this->nChars=6;
        $this->margin_y = 10;

        $this->nlines = 2;
        $this->font_file = 'include/SFOldRepublicSCBold.ttf';
        $this->enc_key="GhsnR5^Hyhsfg";
        $this->captcha_var_name = $captcha_var_name;
 
   }
...
}

The error is thrown in this function

function Create()
    {
        $this->image = imagecreate($this->width, $this->height);
        imagecolorallocate($this->image, 255, 255, 255);

        $this->code = $this->CreateCode();
        return true;
    }

I've tried assigning the value in the first declaration instead of in the function, but I and the captcha image displays correctly but I want to know how to do it "properly".

CodePudding user response:

You need to rename function FGCaptchaCreator($captcha_var_name) to function __construct($captcha_var_name), because since php8.0 methods named same as class are no longer considered as constructors.

Also as var is an outdated language construct I would also add visibility to each property. And if it's clear from code - type-hint properties also, e.g.:

class FGCaptchaCreator extends FG_CaptchaHandler
{
    protected $image;
    protected int $width;
    protected int $height;
    // etc

Visibility and return type-hints for methods should be added too:

public function __construct($captcha_var_name)
public function Create(): bool
  • Related