Inheritance question

Inheritance question

am 19.03.2007 21:03:05 von Craig Hoffman

Hi there,
I could use some help in understanding inheritance and accessing
certain properties in objects.
For example (see below), lets say I would like to use "public $one"
property in a new class / method (such as class b)? What is the
best way to accomplish this? Any help and or suggestions are welcome.

class a {
public $one;

public function someMethod() {
$this->one = '1';
}
}

class b {
public $two

function someOtherMethod() {
$this->two = '2';
}
}

- CH

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

Re: Inheritance question

am 19.03.2007 23:21:06 von Niel Archer

Hi

> For example (see below), lets say I would like to use "public $one"
> property in a new class / method (such as class b)? What is the
> best way to accomplish this? Any help and or suggestions are welcome.
>
> class a {
> public $one;
>
> public function someMethod() {
> $this->one = '1';
> }
> }
>
> class b {
> public $two
>
> function someOtherMethod() {
> $this->two = '2';
> }
> }

At least two ways you could go about it. Most straight forward would
be to inherit, like this:

class a {
public $one;

public function someMethod() {
$this->one = '1';
}
}

class b extends a{
public $two

function someOtherMethod() {
$this->two = '2';
}
}

$object = new b;

$object->someMethod();
$object->someOtherMethod();

print $object->one, $object->two;


In addition to that, if you actually need to use an instance of a
separately to b, you can pass the instance of a into b as a parameter.
Definition for 'b' would need to be something like:

class b {
public $a;
public $two

function __Constructor($dummy) {
$this.a = $dummy;
)

function someOtherMethod() {
$this->two = '2';
}
}

$object1 = new a;
$object2 = new b(&$object1);

$object1->someMethod();
$object2->someOtherMethod();

print $object2->a->one, $object2->two;

There are more than likely other ways to go about this. Check the
documentation for further examples of how to use classes in PHP.

Niel

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