Reputation: 331
class A
{
public $variable
public function someFunction()
{
$this->variable = 'I am a variable';
}
}
class B extends A
{
public function anotherFunction()
{
parent::someFunction();
$stmt = $this->dbc->prepare('INSERT INTO table(row) VALUES(:variable)');
$stmt->bindParam(':variable', $this->variable);
$stmt->execute();
$stmt = null;
$dbc = null;
}
}
How can I inherit $variable
from 'class A' without calling again someFunction()
.
The problem I have is that my 'class A' adds products to the basket and 'class B' inserts them into the database. When I call someFunction()
in 'class B' to get all the product's details stored in properties in 'class A', it adds products to the basket again because the method is called twice, once in 'class A' and then again in 'class B'.
I could just keep all code in one class but that would break the SRP principle, wouldn't it?
EDIT: The code above is just to depict my problem, it's not an exact representation of my real script, hence there's nothing in it related with adding products to a basket. I'm just trying to keep things simple.
Upvotes: 0
Views: 245
Reputation: 13645
Your class A
and class B
are two completely different instances. If you have an instance of class A
, nothing you do in that will be reflected in your class B
instance.
When extending, see it as class B
is a different class that only uses class A
as a base template.
Instead of extending it, you can pass your class A
instance into class B
instance so class B
can get it's data directly from the class A
-instance.
Example:
class A
{
public $var;
public function doStuff()
{
$this->var = 'Foobar';
}
}
class B
{
public function doOtherStuff(A $classA)
{
// Now you can get the data from class a
$var = $classA->var;
// Do you db stuff
}
}
$classA = new A();
$classA->doStuff();
$classB = new B();
$classB->doOtherStuff($classA);
Upvotes: 2