【问题标题】:php chaining method error and confusionphp链接方法错误和混乱
【发布时间】:2018-02-26 10:57:03
【问题描述】:

我正在学习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.";
?>

现在的问题是,当用于调用函数而不调用公共变量 tank 时,它会显示以下错误消息。

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

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

我对此很困惑

【问题讨论】:

  • 您的ride() 方法返回自身,因此$tank 是对$bmw 对象的引用。
  • 你可以使用魔术方法__toString,看看php.net/manual/en/language.oop5.magic.php#object.tostring
  • 你已经复制了书中的代码,“the-essentials-of-object-oriented-php”。在 Chain Method Lesson 中指出,“为了让我们能够执行链接,方法应该返回对象,并且因为我们在类中,所以方法应该返回 $this 关键字。”您可以使用 __toString(),单独调用或设置 getter 方法。

标签: php oop


【解决方案1】:

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

__toString() 魔术函数

类内部

function __toString() {
    return $this->tank;
}

回声呼叫

echo "The number of gallons left in the tank: " . $tank . "gal.";

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

实现一个getter函数

类内部

function getRemainingGallons() {
    return $this->tank;
}

回声呼叫

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

或编辑链式函数

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

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

【讨论】:

  • 为什么不像getRemainingGallons()这样意图更清晰的东西?
【解决方案2】:

换行

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

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

它会按预期工作。

【讨论】:

    【解决方案3】:

    你可以通过两种方式做到这一点,

    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.";
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多