0

I have 3 files, 2 of the files instantiate my myclass class. To determine which file they came from I want to pass a variable through to the class and then be able to output different content.

<?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';
        }


    }

}

?>

I have read up on reflection classes and this article PHP: How to instantiate a class with arguments from within another class but can't seem to get this to work for my scenario.

How can I achieve this?

Community
  • 1
  • 1
bigdaveygeorge
  • 947
  • 2
  • 12
  • 32
  • pass it to `__contruct($var)` and write it to private var. OR write a setter and call that _after_ contructing – Jeff Apr 15 '17 at 09:48

1 Answers1

1

Use this __FILE__ which this will give complete path of the file as an input to your class.

For getting just filename instead of __FILE__ use this explode("/", __FILE__)[count(explode("/", __FILE__))-1]

File 1:

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

File 2:

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

File3

<?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';
        }


    }

}

?>
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42