S
S
supdesign2020-04-20 20:50:28
PHP
supdesign, 2020-04-20 20:50:28

Why are the values ​​of all class properties "overwritten" in the constructor?

It would seem that this code should output an empty string, but the number 6 is displayed - the length of the passed string, which should be stored only in $length

class Decoder{ 
    private $inputStr; 
    private $pos; 
    private $out; 
    private $length; 
     
    public function __construct(string $str) {
        $this->inputStr = $str;        
        $this->$pos = 0;
        $this->$out = '';    
        $this->$length = mb_strlen($str);        
    }   
    public function decode(): string {
        return $this->$out;
    }    
}

$cipher = 'chiper';
$decrypted = new Decoder($cipher); 
echo $decrypted->decode();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2020-04-20
@supdesign

you have a mistake

class Decoder{ 
    private $inputStr; 
    private $pos; 
    private $out; 
    private $length; 
     
    public function __construct(string $str) {
        $this->inputStr = $str;        
        $this->pos = 0; // Было $this->$pos
        $this->out = ''; // Было $this->$out
        $this->length = mb_strlen($str); // Было $this->$length
    }   
    public function decode(): string {
        return $this->out; // // Было $this->$out
    }    
}

In your case $this->$length = mb_strlen($str); => $this->null = mb_strlen($str);
Thus =>return $this->$out;return $this->null // 6

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question