0

I have a public object Let say X. defined in a config file. How could I use this object in a method within a class. I think when I globalize X in that method its looks within the class. :(

include('config.php'); //the objec X is defined here
class MyClass{
 public foo(){
 global $X; // I thing It is looking within the class
 }
}
3
  • So, you can't make use of $x in the foo() method now? Is this local or on a webserver? Is it working outside the class? Commented Oct 26, 2011 at 8:32
  • No, It is in global scope, So you can use it in your method. Commented Oct 26, 2011 at 8:33
  • Could you show us the relevant code inside of config.php? Commented Oct 26, 2011 at 8:58

3 Answers 3

1

I have made a demo...I hope this is what you wanted.. global.php

<?php

$x=5;

?>

index.php

<?php
include('global.php');
class foo{
private $value;
function __construct(){
global $x;
    $this->value=$x;
}
function show(){
    return $this->value;
}
}
$a= new foo();
echo $a->show();
?>
Sign up to request clarification or add additional context in comments.

Comments

0

This works for me:

class LemonSalesman {
    public function advertise() {
        echo 'Get your fresh lemons here!';
    }
}

$LemonSalesman = new LemonSalesman();

class MyObject {
    public function foo() {
        global $LemonSalesman;

        $LemonSalesman->advertise();
    }
}

$MyObject = new MyObject();
$MyObject->foo();

Are you sure your $X object is global?

Comments

0

If you defined $x in your config file in this way:

 <?php
      $x = 'somevalue';
 ?>

then using the global in the function will work just fine. Alternately you could also use the global array to access the variable $GLOBALS['x'], however I'm not sure how common or suggested that is.

However, if you have your configuration variable defined inside a function or class then it would have to have a global there as well for example:

 <?php

      function loadConfig(){
           // no global here means that $x is not global.
           $x = 'somevalue';
      }
 <?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.