【问题标题】:use main file's variable inside class PHP在 PHP 类中使用主文件的变量
【发布时间】:2020-02-01 17:37:15
【问题描述】:

我有一个包含变量的主 php 文件:

$data['username']

正确返回用户名字符串。 在这个主文件中,我包含了一个类 php 文件:

require_once('class.php');

它们似乎很好地联系在一起。 我的问题是:如何在类文件中使用 $data['username'] 值?我需要做一个 if 语句来检查它在该类中的值。

class.php

<?php

class myClass {
    function __construct() {

        if ( $data['username'] == 'johndoe'){   //$data['username'] is null here
          $this->data = 'YES';
        }else{
          $this->data = 'NO';
        }
    }
}

【问题讨论】:

    标签: php wordpress class include


    【解决方案1】:

    有很多方法可以做到这一点,如果我们知道您的主 php 文件和类的外观,我们可以给您准确的答案。一种方法,从我的头顶开始:

    // main.php
    // Instantiate the class and set it's property
    require_once('class.php');
    $class = new myClass();
    $class->username = $data['username'];
    
    // Class.php
    // In the class file you need to have a method
    // that checks your username (might look different in your class):
    class myClass {
    
        public $username = '';
    
        public function __construct() {}
    
        public function check_username() {
            if($this->username == 'yourvalue') {
                return 'Username is correct!';
            }
            else {
                return 'Username is invalid.';
            }
        }
    }
    
    // main.php
    if($class->username == 'yourvalue') {
        echo 'Username is correct!';
    }
    
    // or
    echo $class->check_username();
    

    【讨论】:

    • 所以前两行在主 php 文件中,下面的其他内容在类文件中,对吗?
    • new myClass();在我的情况下应该有什么名字? class.php 文件的名称?比如:新类(); ?
    • new myClass() 应该与class.php 文件中的实际类具有完全相同的名称。这样你就可以指定具体使用哪个类。
    【解决方案2】:

    如果变量是在调用require_once 之前定义的,那么您可以使用global 关键字访问它。

    main.php

    <?php
    $data = [];
    require_once('class.php');
    

    class.php

    <?php
    global $data;
    
    ...
    

    如果您的 class.php 正在定义一个实际的类,那么我会推荐 Lukasz 的答案。

    根据您的更新,我会将数据作为参数添加到构造函数中,并在实例化时传递:

    <?php
    require_once('class.php');
    
    $data = [];
    
    new myClass($data);
    

    调整您的构造函数以具有签名__construct(array $data)

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2016-09-13
      相关资源
      最近更新 更多