Re: Can a class instance a property of another class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ken Kixmoeller -- reply to ken@xxxxxxxxxxxxxx wrote:
> OK, Jochem, I adapted your example and got it working. Thank you very much.
> 
> I am still playing with it to better understand. One thing I don't yet
> understand is the necessity for the getFoo()/getBar() "handshake,"
> especially the getbar() in the BAR class. That doesn't seem to serve any
> purpose. My adaptation us just a getDummy().
> 
> Do they just serve to pass the object by reference?

no - the whole piece of code was just a silly example to show you
that you can stuff an object into the property of another object.

objects are always by reference in php5 - in php4 you have to
use the 'reference' operator (the @ symbol) to make object be passed by reference.

your original question showed a new object being made in the constructor
of another object - that is fine but it seems a little pointless to
worry about referencing some 'global' [connection] object in each relevant
class when you seem to be creating a new object in each constructor.

try this example (I assume you use php5 - which I think you are because
you mentioned using the __construct() method which is a php5 only bit of
functionality):

<?php

class DBConn {
	private $userCnt = 0;
	function incrementUC() { $this->userCnt++; }
	function getUC() { return $this->userCnt;  }
}

class DOExample {
	private $dbconn;

	function __construct() {
		$this->dbconn = getDBConn();
		$this->dbconn->incrementUC();
	}
}

function getDBConn() {
	static $conn;

	if (!isset($conn))
		$conn = new DBConn();
	
	return $conn;
}

$a = new DOExample;
$c = new DOExample;
$b = new DOExample;

$d = getDBConn();
echo $d->getUC(),"\n";

?>

> 
> 
> Ken
> 
> --------------------------------------------------------------
> On Jan 26, 2007, at 5:47 PM, Jochem Maas wrote:
> 
> 
>>
>> class Foo
>> {
>>     private $var;
>>     function __construct() { $this->var = "foo"; }
>>     function getFoo() { return $this->var; }
>> }
>>
>> class Bar
>> {
>>     private $var;
>>     private $foo;
>>     function __construct() { $this->var = "bar"; $this->foo = new Foo; }
>>     function getBar() { return $this->var; }
>>     function speak() { echo "I am
>> ",$this->foo->getFoo(),$this->getBar(),"\n"; }
>> }
>>
>>
> 
> --PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux