How can one class use another?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpNewb
Forum Newbie
Posts: 6
Joined: Fri Feb 03, 2006 2:07 pm

How can one class use another?

Post by phpNewb »

I wrote a mySQL class to handle queries and output results a certain way. Then I have 5 other classes that each do different things but all need to use the mySQL class. I tried to do it like this, but it didn't work:

Code: Select all

class OtherClass {
   var $db = new mySQLClass;

   function getResults($query) {
      $db->Query($query);
   }

}
Yea... that doesn't work. I've been googling for over an hour now. I must be using the wrong keywords. I found "class1 extends class2", but I'm not sure if that's what I need, and if it is, how do I do it? Do I modify each class declaration to look like " class OtherClass extends mySQLClass ", how would I call the mySQLClass methods?

I know this is very newb, and I'm asking many questions. Thanks in advance for your patience.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Read http://www.php.net/oop... Everything you need to know is in there...

Code: Select all

class Foo {
  var $bar;

  function Foo($bar) {
    $this->bar = $bar;
  }

  function DoStuff() {
    this->bar->devnet();
  }
}

$bar = new Bar;
$foo = new Foo($bar);
$foo->DoStuff();
User avatar
wtf
Forum Contributor
Posts: 331
Joined: Thu Nov 03, 2005 5:27 pm

Post by wtf »

you need to make sure file with otherClass includes mySQLClass

Code: Select all

include('path/to/mySQLClass');

class OtherClass { 
   var $db = new mySQLClass; 

   function getResults($query) { 
      $db->Query($query); 
   } 

}
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

wtf wrote:you need to make sure file with otherClass includes mySQLClass

Code: Select all

include('path/to/mySQLClass');

class OtherClass { 
   var $db = new mySQLClass; 

   function getResults($query) { 
      $db->Query($query); 
   } 

}
No. The problem is that you're trying to instantiate the object without using a method. You can only declare properties here... you can't run processes. Do it in the constructor ;)

Code: Select all

<?php

class foo
{
    var $obj;

    function foo()
    {
        $this->obj = new someClass;
    }
}

?>
Post Reply