php链接方法错误和混乱

Ind*_*nil 2 php oop

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

<?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.";
?>
Run Code Online (Sandbox Code Playgroud)

现在问题是当用于调用函数而不调用Public变量时,tank它显示以下错误消息.

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

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

我很困惑

Mar*_*her 5

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

__toString()魔术函数

在课堂里面

function __toString() {
    return $this->tank;
}
Run Code Online (Sandbox Code Playgroud)

回音电话

echo "The number of gallons left in the tank: " . $tank . "gal.";
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/language.oop5.magic.php#object.tostring

实现一个getter函数

在课堂里面

function getRemainingGallons() {
    return $this->tank;
}
Run Code Online (Sandbox Code Playgroud)

回音电话

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

或编辑链接功能

$tank = $bmw -> fill(10) -> ride(40) -> getRemainingGallons();
Run Code Online (Sandbox Code Playgroud)

确保为您的方法选择一个清晰的名称,以便您始终知道它的作用.

  • 为什么不像"getRemainingGallons()"那样具有更明确意图的东西? (2认同)