【问题标题】:How do I pass a variable during class instantiate in one file to another?如何在一个文件中的类实例化期间将变量传递给另一个文件?
【发布时间】:2017-04-15 09:45:39
【问题描述】:

我有 3 个文件,其中 2 个文件实例化了我的 myclass 类。为了确定它们来自哪个文件,我想将一个变量传递给类,然后能够输出不同的内容。

<?php

// File 1

$file1variable = '1';
$go = new myclass( $file1variable );

// File 2

$file2variable = '2';
$go = new myclass( $file2variable );

// File3

class myclass {

    public function __construct() {
        $this->display();
    }

    public function display() {

        if( $file1variable ) {
            echo 'file1';
        } elseif( $file2variable ) {
            echo 'file2';
        }


    }

}

?>

我已经阅读了反射类和这篇文章PHP: How to instantiate a class with arguments from within another class,但似乎无法让它适用于我的场景。

我怎样才能做到这一点?

【问题讨论】:

  • 将其传递给__contruct($var) 并将其写入私有变量。或者编写一个 setter 并在 构建之后调用它

标签: php class oop variables


【解决方案1】:

使用这个__FILE__,它将提供文件的完整路径作为类的输入。

要获取文件名而不是 __FILE__,请使用此 explode("/", __FILE__)[count(explode("/", __FILE__))-1]

文件 1:

<?php
$go = new myclass( __FILE__ );
?>

文件 2:

<?php
$go = new myclass( __FILE__ );

文件3

<?php
class myclass {

    public function __construct($filename) {
        $this->display($filename);
    }

    public function display($filename) {

        if( $filename == 'some_x.php' ) {
            echo 'file1';
        } elseif( $filename == 'some_y.php') {
            echo 'file2';
        }


    }

}

?>

【讨论】:

  • 谢谢,我将使用变量而不是__FILE__,但原则对我有用:)
  • @bigdaveygeorge 欢迎 .. :)
猜你喜欢
  • 2015-05-22
  • 2021-01-21
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多