Reparsing when variables are redifined

Here is example code:


<?php


$pet_type['0'] = 'dog';
$pet_type['1'] = 'cat';
$pet_type['2'] = 'goldfish';
$pet_type['3'] = 'turtle';

$my_pet_type = $pet_type['0'];

$pet['0'] = "My pet is  a $my_pet_type.";

//echo 1
echo $pet['0']. '<br />';

$my_pet_type = $pet_type['1'] ;

//echo 2
echo $pet['0']. '<br />';

?>

Is there a way to make $pet[‘0’] fill ‘cat’ for the ‘echo 2’ when the variable $my_pet_type is redefined?

What I want is


My pet is a dog.
My pet is a cat.

What happens


My pet is a dog.
My pet is a dog.

When strings (e.g. “my pet is a dog.”) are defined, they are stored simply as series of characters. When you concatenate (‘glue’) a variable into a string, those characters are added to that string. By then changing the initial variable AFTER it’s been concatenated, the string is unchanged.

You can get around this by using a function instead of the variable:

function myPet($Pet){
    return '<p>My pet is a ' . $Pet . '.</p>';
}
echo myPet('dog');
echo myPet('cat');
$my_pet = 'dog';
echo myPet($my_pet);
$my_pet = 'cat';
echo myPet($my_pet);