2

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!

2
  • As a side note, it seems you are using PHP 4 ; that version is not maintained anymore (not even security fixes) ; if you can, it would be better switching to PHP 5.x -- if you are not already running PHP 4 code on PHP 5, which is fine too ^^ Commented Jul 20, 2009 at 17:31
  • I hear you friend :-) my company is waiting to upgrade because they're worried their legacy code won't work on a php5 server. Commented Jul 20, 2009 at 19:45

2 Answers 2

6

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".

Sign up to request clarification or add additional context in comments.

Comments

1

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();   

    }
}
?>

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.