tags:

views:

162

answers:

2

Hi. Is it possible to use an object that was created during a class' construction within the member methods of that class?

Ex

<?php
include ('AClass.php');

class Auto_Cart {
    function Auto_Cart() {
       $aclass = new AClass();
    }

    function DoSomething() {
       $aclass->amemberfunction();   

    }
}
?>

When I call DoSomething, it should call aclass->amemberfunction()

I think my syntax is wrong but maybe this just isn't possible. Can you help me out?

Thanks!

+1  A: 

You need to store a reference to the object in order to use it later, as it will be lost when the constructor function exits. Try storing it as a member of your Auto_Cart object, like this:

<?php
include ('AClass.php');

class Auto_Cart {
    function Auto_Cart() {
       $this->aclass = new AClass();
    }

    function DoSomething() {
       $this->aclass->amemberfunction();   

    }
}
?>
zombat
+6  A: 

You need to store the instance of AClass as a member variable (aka "property") of the instance of Auto_Cart.

Assuming PHP4 by the style of your constructor

class Auto_Cart
{
    /** @var $aclass AClass */
    var $aclass;

    function Auto_Cart()
    {
       $this->aclass = new AClass();
    }

    function DoSomething()
    {
       $this->aclass->amemberfunction();
    }
}

An just as an FYI, in OOP-speak we call this composition - meaning one object creates and stores a reference to another object automatically or "lazily".

Peter Bailey
+1 for UML terminology.
Babak Naffas