如何创建简单的功能?

Why is this working...

$animal='';
    $animal .= "You edited this animal: ";
    if ($data['horse'] != $horse){
        $animal .= 'Name from "'.$data['horse'].'" into "'.$horse.'"';
    }   
    $sql = "INSERT INTO animal (animal,id) values(?,?)";
    $q = $pdo->prepare($sql);
    $q->execute(array($animal,$id));

(Result: "You edited this animal: Mustang into Marwari")

...but this...

$animal='';
$animal .= "You edited this animal: ";  
function animal_func($label, $orig, $edit) {
    if ($orig != $edit){
        $animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
    }
}
animal_func("Name",$data['horse'],$horse);

$sql = "INSERT INTO animal (animal,id) values(?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($animal,$id));

(Result: "You edited this animal: ")

... is not working

Because of the scope of the $animal variable. http://php.net/manual/en/language.variables.scope.php

You need to pass an return the $animal var : /* if you need this only once, outside is better */ $animal .= "You edited this animal: ";

function animal_func($label, $orig, $edit, $animal) { 
    if ($orig != $edit){
        $animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
    return $animal;
    }
}


$animal = animal_func("Name",$data['horse'],$horse,$animal);

You can also do that, perhaps more readable :

function animal_func($label, $orig, $edit, $animal) {
    if ($orig != $edit) {
        $animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
        return $animal;
    }
}

$animal = "You edited this animal: ";
$animal = animal_func("Name",$data['horse'],$horse,$animal);

After another read (this is better):

function animal_func($label, $orig, $edit) {
    if ($orig != $edit) {
        return $label.' from "'.$orig.'" into "'.$edit.'"';
    }
}

$animal = "You edited this animal: ".animal_func("Name",$data['horse'],$horse);

Put this animal into function

function animal_func($label, $orig, $edit) {
    $animal='';
    $animal .= "You edited this animal: ";
    if ($orig != $edit){
        $animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
    }
}
animal_func("Name",$data['horse'],$horse);

or

Declare

global $animal='';
$animal .= "You edited this animal: ";

Because of the scope of your $animal inside your animal_func() is limited to that function only.

What you need to do is pass $animal as reference variable in your animal_func(). So your function should look like:

$animal='';
$animal .= "You edited this animal: ";  
function animal_func($label, $orig, $edit, &$animal) {
    if ($orig != $edit){
        $animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
    }
}
animal_func("Name",$data['horse'],$horse, $animal);

See PHP manuals for variable scope and variable pass by reference on this link.