Jump to content

instantiate a class within a class once


papacostas

Recommended Posts

Ok I have a problem which i assume is not that complicated,

but it is for me... ;)

 

I have a class called Display that makes calls to a database access class called DAO

where all the SQL code is and the logic for fetching the data.

 

I've always been instantiating this class for every function, (like this)

 

  require_once(classname)

  $DAO = new DAO();

 

which is not very good. so now i want to figure out a way to just do it once

in the beginning of the class and then access is whenever i want to

 

i've played around with constructors, autoload and global variables without getting the result i want.

what can i do?

 

here is a snippet of the class i currently use,

it works fine for fetching single row data but multiple records i will need to access the FetchArray class from the DAO

which fetches the mysql array.

 

any comments are greatly appreciated

 

 

class Display {

 

function getDBArray($function, $id) {

$getArray = call_user_func(array($DAO, $function), $id);

$return = $DAO->fetchArray($getArray);

return $return;

}

function postDBArray($function, $values) {

$postArray = call_user_func(array($DAO, $function), $values);

}

        function getUserInfo($id){

$user = $this->getDBArray('getUserInfo', $id);

echo hello $user['name'] ;

}

}

Link to comment
Share on other sites

<?php

  class a {

    function foo() {
      echo "foo";
    }

  }

  class b {

    private $a;

    function __construct() {
      $this->a = new a;
    }

    function bar() {
      $this->a->foo();
    }

  }

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.