TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   How to call classes? (http://www.talkphp.com/advanced-php-programming/3914-how-call-classes.html)

Jenski 01-26-2009 11:00 AM

How to call classes?
 
I have this setup:

class a
class b extends a

class c
class d extends c


I want class d to be able to call several functions in class b.
What is the best way of doing this?

CoryMathews 01-26-2009 02:20 PM

either pass class b to class d by reference or just have class d create a class b within it.

Tanax 01-26-2009 09:26 PM

I would pass it as a reference.

PHP Code:

class extends c
{
private 
$classB;

public function 
setClassB($class)
{

if(
is_object($class)
{
$this->classB $class;
}

}



PHP Code:

$b = new classB();
$d = new classD();
$d->setClassB($b); 

Or you could design it to be added in the __construct function so you would simply use this:
PHP Code:

$b = new classB();
$d = new classD($b); 

And to use the class b functions inside your class d, you just do like this:
PHP Code:

$result $this->classB->function($args); 


Jenski 02-04-2009 10:22 AM

Quote:

Originally Posted by Tanax (Post 21435)

Or you could design it to be added in the __construct function so you would simply use this:
PHP Code:

$b = new classB();
$d = new classD($b); 

And to use the class b functions inside your class d, you just do like this:
PHP Code:

$result $this->classB->function($args); 


Could you create it in the __construct function? Instead of passing, or would that not work? e.g.

PHP Code:

class classD
{
private 
$classB;

public function 
__construct()
{
require_once(
'/path/to/classB/file');
$this->classB = new classB;
}  

$d = new classD(); 


Tanax 02-04-2009 11:53 AM

Yes you can, but I would not advise it.
Sometimes the classes you want to include(for example a DB class), you need to set that class up with some basic values, in this example(the db class) you need to connect and select a db before you can use it. And if you have it instanciated in the __construct, you need to pass all the DB values to that class.

Not to mention, it will be harder for you to use it in another class.
It's easier to pass it as a reference, because then you can set it up before you pass it, plus you can pass it to several different classes.

I'm not saying that my solution is the best in your case, but generally, you want to do how I said. Not good to learn bad habbits, they're so hard to get rid of.


All times are GMT. The time now is 06:20 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0