Search code examples
phpvariablesprotected

PHP Protected variables don't work for me


i'm having trouble with protected variables in PHP. Why doesn't work this code? It keeps showing me error 500. Here's the code:

<?php
class A
{
    protected $variable;
}

class B extends A
{
    $this->variable = 'A';
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <!-- Code -->
    </body>
</html>

Thanks


Solution

  • You can't put instructions like attributions at body of class. Only members definitions are allow. Put the $this->variable = 'A'; inside a method.

    Change:

    class B extends A
    {
        $this->variable = 'A';
    }
    

    To:

    class B extends A
    {
        public function __construct(){
            $this->variable = 'A';
        }
    }