Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php链接方法错误和混乱_Php_Oop - Fatal编程技术网

php链接方法错误和混乱

php链接方法错误和混乱,php,oop,Php,Oop,我正在学习phpoop,但现在我遇到了一个错误,并且对链式方法感到困惑。这是我的密码 <?php class Car { public $tank; public function fill($float) { $this-> tank += $float; return $this; } public function ride($float) {

我正在学习
phpoop
,但现在我遇到了一个错误,并且对链式方法感到困惑。这是我的密码

<?php
    class Car {
        public $tank;

        public  function fill($float) {
            $this-> tank += $float;
            return $this;
        }


        public  function ride($float) {
            $miles = $float;
            $gallons = $miles/50;
            $this-> tank -= ($gallons);
            return $this;
        }
    }


    $bmw = new Car(); 
    $tank = $bmw -> fill(10) -> ride(40);// -> tank;
    echo "The number of gallons left in the tank: " . $tank . " gal.";
?>

现在的问题是,如果在调用函数时不调用公共变量
tank
,则会显示以下错误消息

可捕获的致命错误:无法将Car类的对象转换为 第33行C:\xampp\htdocs\oop\chain.php中的字符串

在这种情况下,为什么在调用这两个函数时调用公共变量
tank
?如果我没有将任何值直接赋给公共变量
tank
,那么我为什么要调用该变量


我对此感到非常困惑

您的方法
ride
返回类
Car
的实例,因此如果您回显它,则尝试直接回显现有的类实例。您现在有两个选择:

__toString()魔术函数 课堂内部

function __toString() {
    return $this->tank;
}
function getRemainingGallons() {
    return $this->tank;
}
回声呼叫

echo "The number of gallons left in the tank: " . $tank . "gal.";
echo "The number of gallons left in the tank: " . $tank->getRemainingGallons() . " gal.";

实现一个getter函数 课堂内部

function __toString() {
    return $this->tank;
}
function getRemainingGallons() {
    return $this->tank;
}
回声呼叫

echo "The number of gallons left in the tank: " . $tank . "gal.";
echo "The number of gallons left in the tank: " . $tank->getRemainingGallons() . " gal.";
或编辑链接函数

$tank = $bmw -> fill(10) -> ride(40) -> getRemainingGallons();
确保为您的方法选择一个清晰的名称,以便您始终知道它的作用。

替换该行

$tank = $bmw -> fill(10) -> ride(40);// -> tank;


它将按预期工作。

您可以通过两种方式来实现

1) 直接访问公共变量

$tank->tank
2) 为这类对象创建一个getter方法

public function getVolume() {
    return $this->tank;
}
然后通过下面的方法访问此

echo "The number of gallons left in the tank: " . $tank->getVolume() . " gal.";<br>
echo "The number of gallons left in the tank: " . $tank->tank . " gal.";
echo“油箱中剩余的加仑数:”$储罐->获取容积()。“gal.”
echo“油箱中剩余的加仑数:”$坦克->坦克。“gal.”;
你的
ride()
方法返回自身,因此
$tank
是对
$bmw
对象的引用。你可以使用magic方法
\uu toString
,看看你从《面向对象php的要点》一书中复制的代码。在Chain方法课程中指出,“为了使我们能够执行链接,方法应该返回对象,并且由于我们在类中,方法应该返回$this关键字。”您可以使用uu toString(),单独调用或设置一个getter方法。为什么不使用像
getRemainingGallons()
这样意图更明确的方法呢?