我为什么需要“&”?

时间:2012-05-13 07:18:45

标签: php oop

请参阅网上有关PHP工厂模式的示例。

$kind =& Vehicle::category($wheel);行中,我为什么要使用&

代码:

<?php
    class Vehicle {

        function category($wheel = 0) {
            if ($wheel == 2) {
                return "Motor";
            } elseif($wheel == 4) {
                return "Car";
            }
        }
    }

    class Spec {

        var $wheel = '';

        function Spec($wheel) {
            $this->wheel = $wheel;
        }

        function name() {
            $wheel = $this->wheel;
                return Vehicle::category($wheel);
        }

        function brand() {
            $wheel = $this->wheel;
                $kind =& Vehicle::category($wheel);
            if ($kind == "Motor") {
                return array('Harley','Honda');
            } elseif($kind = "Car") {
                return array('Nisan','Opel');
            }
        }
    }

    $kind = new Spec(2);
    echo "Kind: ".$kind->name();
    echo "<br>";
    echo "Brand: " . implode(",", $kind->brand());
?>

2 个答案:

答案 0 :(得分:5)

来自Stack Overflow问题 Reference - What does this symbol mean in PHP?

=&参考文献

正如(已删除)评论所述,最后一个链接应适用于您的具体案例。

答案 1 :(得分:4)

这里没用,因为示例是获取对常量的引用,但是references当你想要“观察”可能会改变的值并希望你的变量随之改变时,它们会有用途吗?