Kolvin
Kolvin

Reputation: 185

Call a declared variable inside another function in a PHP Class

I have the following for Caesar Cipher task I'm doing.

class Caesar
{
    protected $secretMessage = 'calvin';
    protected $splitUpMessage;
    protected $splitUpText;
    protected $alphabet=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    private $key = 5;
    protected $encryptedText;

    public function encrypt()
    {
        $alphabet = $this->alphabet;
        $secretMessage = $this->secretMessage;
        $splitUpMessage = $this->splitUpMessage;
        $key = $this->key;

        $splitUpMessage = str_split($secretMessage);
        $flip = array_flip($alphabet);
        $messageCount = strlen($secretMessage);

        foreach ($splitUpMessage as $singleChar) {
            $encryptedText = $alphabet[($flip[$singleChar]+$key)%26];
            print_r($encryptedText);
        }

        echo PHP_EOL;
    }

    public function decrypt()
    {
        $alphabet = $this->alphabet;
        $encryptedText = $this->encryptedText;
        $splitUpText =  $this->splitUpText;
        $key = $this->key;

        $splitUpText = str_split($encryptedText);
        $keyFlip = array_flip($alphabet);
        $charCount = strlen($encryptedText);
    }
}

$encrypt = new Caesar();
// $encrypt->encrypt();
$encrypt->decrypt();

So basically what I want to do is be able to call my $encryptedText in my decrypt function. I'm not sure how to do it though. Globally? PHP noob here.

Thanks for any help/advice.

Upvotes: 0

Views: 64

Answers (2)

Henry
Henry

Reputation: 46

Replace all $encryptedText with $this->encryptedText in two functions.

Upvotes: 1

Marc B
Marc B

Reputation: 360622

Store it back into the object:

public function encrypt() {
    ... blah blah blah
    $this->encryptedtext = $temporary_working_local_copy;
}

Upvotes: 1

Related Questions