呼叫参数多少次



我只是一个人学习PHP,我有一个问题,希望您能够提供帮助。

拳头样式

<?php
class Fist_style
{
    function method_1()
    {
        global $a;
        return $a + 1; 
    }
    function method_2()
    {
        global $a;
        return $a - 1;
    }
    function method_3()
    {
        $call_1 = $this->method_1();
        $call_2 = $this->method_2();
    }
    // In this case, how many times $a was called?
}

第二样式

<?php
class Second_style
{
    function method_1($a)
    {
        return $a + 1; 
    }
    function method_2($a)
    {
        return $a - 1;
    }
    function method_3()
    {
        global $a;
        //I will call both method_1 and method_2
        $call_1 = $this->method_1($a);
        $call_2 = $this->method_2($a);
        //............
    }
    // In this case, how many times $a was called
}
?>

问题在我的代码中,开发时哪种样式会更好?

使用Globals通常是灾难的秘诀 - 因为许多有经验的人都乐于告诉您。

在课堂中拥有状态的正常方式是宣布类属性:

<?
class MyClass
{
    public $a;
    function __construct($valueForA) {
        $this->a = $valueForA;
    }
    function increment()
    {
       $this->a += 1; 
    }
    function decrement()
    {
       $this->a -= 1; 
    }
    function plusminus()
    {
        $this->increment();
        $this->decrement();
    }
}

可以像这样使用:

$anInstance = new MyClass(10); // sets a to 10 by calling the __construct method
$anInstance->increment();
echo($anInstance->a); // 11
$anInstance->decrement();
echo($anInstance->a); // 10

在此处阅读有关PHP中OOP的更多信息。

至于您的代码中的问题,$a不是一种方法,因此不能被称为。

另外,return $a -1;不更改全局$a(不确定这是否是意图)。

编辑

如果您的功能增加,例如

function increment ($var) {
    $var = $var - 1;
    return $var;
}

然后,$var作为值传递 - 如果您在5中传递,则PHP仅关心5,而不是名称。示例:

$a = 5;
$incremented = increment($a);
echo($a); // echoes 5;
echo($incremented); //echoes 6

我建议在php中读取范围。

最新更新