Using global within a class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin Lucas-Smith

    Using global within a class



    I have a class from within which other classes are called.

    In the constructor, I want to create an instance of a database connection,
    so that this database can be called elsewhere.

    <?php
    # Declare a class foo
    class foo
    {
    # Constructor
    function foo
    {
    # Load the class file
    require_once ('database.clas s.php');

    # Create a database object
    $database = new database ();
    }


    # Function to do work
    function doWork ()
    {
    # Get the database object
    global $database;

    # Call some method from within bar
    echo $database->doSomethingEls e ();
    }
    }
    ?>

    If I now create an instance of that object:

    <?php
    # Create a foo
    $foo = new foo ();

    # Get foo to do stuff
    $foo->doWork ();
    ?>


    ... this doesn't work. Instead, I get:

    Fatal error: Call to a member function doSomethingElse () on a
    non-object in {filename} on line {line number}


    Basically the global isn't picking things up from the rest of the class.

    Normally I would use the standard $this-> system, but the problem is that
    accessing the database could be several levels deep.

    Any idea how I can make use of a global variable without having to
    continually pass the object between functions, i.e.

    function doWork ($database)
    echo $database->doSomethingEls e ();
    }

    constantly?


    Martin
  • Jacques Tôle

    #2
    Re: Using global within a class

    Am Tue, 10 Aug 2004 18:11:35 +0100 schrieb Martin Lucas-Smith:
    [color=blue]
    >
    > Normally I would use the standard $this-> system, but the problem is that
    > accessing the database could be several levels deep.
    >[/color]

    what kind of problem would that be?

    Comment

    • Pieter Nobels

      #3
      Re: Using global within a class

      Martin Lucas-Smith wrote:[color=blue]
      >
      >
      > I have a class from within which other classes are called.
      >
      > In the constructor, I want to create an instance of a database
      > connection, so that this database can be called elsewhere.
      >[/color]

      Variables in functions are destroyed when the function is finished. You
      have to define your variable outside the class and do global $database;
      everywhere you need it. It also might be interesting to (re)read the
      part about scopes in the PHP Manual.

      --
      Pieter Nobels

      Comment

      Working...