Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.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 OOP,如何正确使用函数参数_Php_Oop - Fatal编程技术网

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

PHP OOP,如何正确使用函数参数,php,oop,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") {

我有一个小问题,我将解释代码下的所有内容:

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

?>
但它不起作用,我会出错:

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

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


你知道如何让代码按我想要的方式工作吗?

如果你试图用
Punch
方法进行计算,问题是你调用
Punch
时没有传递
Fighter
对象。您正在传递字符串
$name
属性。所以使用

$fighter->Punch($enemy);
而不是

$fighter->Punch($enemy->name);
如果您传递的是
Fighter
对象,那么您尝试使用的计算应该可以工作,但是您需要对
Punch
方法中的输出进行一些调整,例如,使用
$敌军->name
而不是
$敌军

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) {...

当我这样做时,我得到了错误:可捕获致命错误:类战斗机的对象无法转换为stringReplace
$Foreign
,在
echo
中使用
$Foreign->name
以后,您应该指出导致错误的行。行号在错误消息中。
public function Punch(Fighter $enemy) {...