Doc_1faux
Doc_1faux

Reputation: 161

Access variable defined in other file from class

I would like to know if there is a way to access a variable defined in an other file from a class in PHP.

Example :

file_01.php

<?php
    $a = 42;
?>

file_02.php

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

    class mnyClass
    {
        private $myVar;

        function __construct($var = $a)
        {
            $this->myVar = $var;
        }

        function getVar()
        {
            return $this->var;
        }

        function setVar($var)
        {
            $this->myVar = $var;
        }
    }
?>

Obviously, my class is more complicated. I have chosen this example for a better comprehension of what I try to do ;)

Thank you in advance.

Upvotes: 2

Views: 3668

Answers (4)

Doc_1faux
Doc_1faux

Reputation: 161

Finally, I use this method :

<?php

require_once('file_01.php');

class myClass {

    private $myVar;

    function __construct($var = NULL)
    {
        global $a;

        if($var == NULL)
            $this->myVar = $a;
        else
            $this->myVar = $var; 
    }
}

?>

I declare my variable $a as global in the constructor, set the default value of my $var to NULL and check if the constructor was called with parameter(s) ($var == NULL).

Upvotes: 0

Steve
Steve

Reputation: 350

You could access the variable via GLOBALS:

http://php.net/manual/en/language.variables.scope.php

EDIT: a little more detail-

function __construct() {
  $this->myVar = $GLOBALS['a'];
}

Upvotes: 2

Alex Howansky
Alex Howansky

Reputation: 53636

It sounds like you're setting up some application defaults. It might make sense to define these as constants:

file_01.php:

define('DEFAULT_VALUE_FOR_A', 42);

file_02.php

class myClass
{
    function __construct($var = DEFAULT_VALUE_FOR_A) {
    }
}

Upvotes: 1

Naftali
Naftali

Reputation: 146350

You cannot do this:

    function __construct($var = $a)
    {
        $this->myVar = $var;
    }

What you can do is pass it:

<?php
    require_once('file_01.php');
    $mnyClass = new mnyClass($a);// the torch has been passed!

    class mnyClass
    {
        private $myVar;

        function __construct($var = null)
        {
            $this->myVar = $var;
        }

        function getVar()
        {
            return $this->var;
        }

        function setVar($var)
        {
            $this->myVar = $var;
        }
    }
?>

OR you can do this (it is not advisable):

    function __construct($var = null)
    {
        if($var === null) $var = $GLOBALS['a']; //use global $a variable
        $this->myVar = $var;
    }

Upvotes: 3

Related Questions