PHP将对象属性作为方法参数传递

时间:2015-02-25 18:49:12

标签: php function methods

.Hello!我想弄清楚为什么我不能使用

$myCar = get_path_from_letter($car->letter);

get_path_from_letter使用开关根据传递的字母返回字符串:

$car->get_path_from_letter = function($letter){
     $path = "";
switch($letter){
 case 'a':
$path = $car->A;
break;

case'b':
$path = $car->B;
break;
}
return $path;
};

如果有人能够解释我出错的地方或提供指向哪个方向的话,我们将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:2)

通过使用传递$ car:

$car->get_path_from_letter = function($letter) use ($car){
    $path = "";
    switch($letter){
        case 'a':
            $path = $car->A;
            break;
        case'b':
            $path = $car->B;
            break;
    }
    return $path;
};