简体   繁体   English

在 class PHP 中使用主文件的变量

[英]use main file's variable inside class PHP

i have a main php file which contains the variable:我有一个包含变量的主要 php 文件:

$data['username']

which returns the username string correctly.正确返回用户名字符串。 In this main file i included a class php file with:在这个主文件中,我包含了一个 class php 文件:

require_once('class.php');

they seem linked together well.他们似乎很好地联系在一起。 My question is: how can I use the $data['username'] value inside the class file?我的问题是:如何在 class 文件中使用$data['username']值? I'd need to do an if statement to check its value inside that class.我需要做一个 if 语句来检查它在 class 中的值。

class.php class.php

<?php

class myClass {
    function __construct() {

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

There are many ways to do that, we could give you accurate answer if we knew how your main php file and the class look like.有很多方法可以做到这一点,如果我们知道您的主要 php 文件和 class 的样子,我们可以给您准确的答案。 One way of doing it, from the top of my head:从我的头顶开始,一种方法是:

// 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();

If the variable is defined before the call to require_once then you could access it with the global keyword.如果变量是在调用require_once之前定义的,那么您可以使用global关键字访问它。

main.php main.php

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

class.php class.php

<?php
global $data;

...

If your class.php is defining an actual class then I would recommend Lukasz answer.如果您的 class.php 正在定义实际的 class ,那么我会推荐 Lukasz 的答案。

Based on your update I would add the data as a parameter in the constructor and pass it in on instantiation:根据您的更新,我会将数据作为参数添加到构造函数中,并在实例化时将其传递:

<?php
require_once('class.php');

$data = [];

new myClass($data);

Adjusting your constructor to have the signature __construct(array $data)调整您的构造函数以具有签名__construct(array $data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM