PHP OOP,如何正确使用函数参数

时间:2018-02-20 21:11:04

标签: php oop

我有一点问题,我会在代码下解释一切:

<?php
class Fighter {
    public $name;
    public $health = 100;
    public $power;
    public $mainhand;

    public function Punch($enemy) {
        $arm = rand(0, 1);
        if($this->mainhand == "R") {
            if($arm == 1) {
                $this->power = $this->power * 2;
            }
        }
        else if($this->mainhand == "L") {
            if($arm == 0) {
                $this->power = $this->power * 2;
            }
        }

        switch($arm) {
            case 0:
                $arm = "left";
                $this->power = rand($this->power - 2, $this->power + 2);
                echo $this->name . " hits " . $enemy . " with " . $arm . " arm and deals " . $this->power . " damage";
                break;
            case 1:
                $arm = "right";
                $this->power = rand($this->power - 2, $this->power + 2);
                echo $this->name . " hits " . $enemy . " with " . $arm . " arm and deals " . $this->power . " damage";
                break;
        }

    }
}

$fighter = new Fighter();
$fighter->name = "John";
$fighter->power = 7;
$fighter->mainhand = "R";

$enemy = new Fighter();
$enemy->name = "Matt";
$enemy->power = 6;
$enemy->mainhand = "L";

$fighter->Punch($enemy->name);
echo "<br>";
$enemy->Punch($fighter->name);
echo "<br><br>";

echo $fighter->name . " - " . $fighter->health . "HP";
echo "<br>";
echo $enemy->name . " - " . $enemy->health . "HP";

?>

让我解释一下这段代码,这里有2&#34;战士&#34; (对象),一切都很好,除了我想要做的,例如约翰击中马特,马特会失去健康,我试着这样做:

$enemy->health = $enemy->health - $this->power;

但它不起作用,我得到错误:

  

注意:尝试获取非对象的属性

     

警告:尝试分配非对象的属性

您是否有任何想法如何使代码按我想要的方式工作?

1 个答案:

答案 0 :(得分:2)

如果您尝试在Punch方法中进行该计算,则问题是您在致电Fighter时未传递Punch对象。您正在传递字符串$name属性。所以使用

$fighter->Punch($enemy);

而不是

$fighter->Punch($enemy->name);

如果您改为通过Fighter对象,则您尝试使用的计算应该有效,但您需要对Punch方法中的输出进行一些调整,例如使用$enemy->name代替$enemy

echo $this->name . " hits " . $enemy->name . " with " . $arm . " arm and deals " . $this->power . " damage";
//     access the name property here ^^  since $enemy is no longer a string

如果你偶然做到这一点,你可以通过方法签名中的提示战斗机类型来捕捉将来的错误。

public function Punch(Fighter $enemy) {...