SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict richtestani's Avatar
    Join Date
    Nov 2003
    Location
    Bridgeport
    Posts
    292
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Reusing Objects on included files

    I'm working on a project and coming across an issue.

    I have a template where I create a new instance of an object

    Code:
    $myOb = new Object();
    I also include other files in the template based on other criteria.
    But I want to check for a condition or value in the class by calling a method.
    When I try to do this in the included file I get an error.

    Code:
    Call to a member function myMethod() on a non-object
    I am assuming, the included file has no idea about the created object. Does this mean on every included file I need to create a new instace? If I name it the same, is there any sort of collision?

    Thanks
    Rich
    RichTestani
    -------------------------------
    http://www.junkdepot.com
    http://www.rareoopdvds.com | The Movie Poster Site

  2. #2
    SitePoint Addict Trent Reimer's Avatar
    Join Date
    Sep 2005
    Location
    Canada
    Posts
    228
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well if it helps your bug hunt, included files can be aware of created objects.

    e.g.

    (file: 'myclass.php')
    PHP Code:
    <?php
    class MyClass
    {
        function 
    myMethod()
        {
            echo 
    "Hi. This is my method of my class.\n";
        }
    }
    ?>
    (file: 'script.php')
    PHP Code:
    <?php
    // Include the class definition
    include_once('myclass.php');

    // Instantiate an instance
    $myObject = new MyClass();

    // Attempt to use the instance
    include('include.php');
    ?>
    (file: 'include.php')
    PHP Code:
    <?php
    $myObject
    ->myMethod();
    ?>

    If you run 'script.php' you can see the included file invoking the method of the instantiated object. The order is important though. If '$myObject' is not instantiated before the included file tries to access it there is an error:

    "Fatal error: Call to a member function myMethod() on a non-object..."


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •