Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.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 如何访问主页面导入的类中的变量?_Php - Fatal编程技术网

Php 如何访问主页面导入的类中的变量?

Php 如何访问主页面导入的类中的变量?,php,Php,我正在寻找从同一类中的另一个函数访问函数中变量的方法。我搜索的是使用全局变量。当我在同一页(而不是类)上创建方法和打印代码时,它工作得很好,但当我在类中分离这些方法并从主页调用它们时,它就不起作用了 哦..我刚刚发现我不能使用全局变量,因为每次在主页上的表中迭代I_type()方法时,$rand_类型应该是不同的。我需要在两种方法中使用相同的$rand_type值 (情况是……在我的游戏中,我将首先随机打印不同类型的项目,然后单击其中一个以随机确定类别和级别。) 我怎样才能解决它 class I

我正在寻找从同一类中的另一个函数访问函数中变量的方法。我搜索的是使用全局变量。当我在同一页(而不是类)上创建方法和打印代码时,它工作得很好,但当我在类中分离这些方法并从主页调用它们时,它就不起作用了

哦..我刚刚发现我不能使用全局变量,因为每次在主页上的表中迭代I_type()方法时,$rand_类型应该是不同的。我需要在两种方法中使用相同的$rand_type值

(情况是……在我的游戏中,我将首先随机打印不同类型的项目,然后单击其中一个以随机确定类别和级别。)

我怎样才能解决它

class Item {

    function i_type() {
        $rand_type = rand(1,8);
        // some other codes below..
        return $some_data;
    }

    function i_buy() {

        $rand_class = rand(1,3);
        $rand_level = rand(1,5);
        // some other codes below..
        return $some_data;
    }
}

您可以设置
private
public
变量(private更安全,但访问受限)

然后在创建类的实例后调用任何函数

$class = new Item();
$rand_level = $class->getRandLevel();
$setlvl = 5;
$class->setRandLevel($setlvl);

这就是所谓的封装。但这是一个更高的概念。私有/公共变量是这样访问的。

您可以通过以下方式访问变量:

  • 公开
  • 吸气剂

    class Item {
    
    private $rand_type;
    private $rand_class; 
    private $and_level;
    
    public function setRandType($type){  $this->rand_type =$type ;}
    
    public function getRandType(){ return $this->rand_type ;}
    
    
    public function i_type() {
        $this->rand_type = rand(1,8);
        // some other codes below..
        return $some_data;
    }
    
    public function i_buy() {
    
        $this->rand_class = rand(1,3);
        $this->rand_level = rand(1,5)
        // some other codes below..
        return $some_data;
    }
    
      }
    
因此,您可以实例化您的对象:

 $item = new Item();

当您调用
$item->i_type()
然后调用
$item->getRandType()
时,您将从
i_buy()

类项目{private$rand\u level;函数foo()中获得rand值{$this->rand_level…
返回私有/受保护变量的函数很愚蠢,如果需要访问它,只需将其公开,节省创建冗余方法显然这些不是您的方法,但它可以帮助将来的分配/项目,并且很容易操纵您的类来使用此概念
 $item = new Item();