This's my second question, even thought, i answered the previous one, on my own. Anyway, I have a basic problem with OOP, on how to call a non-static method from another class. example: We have a class named A in a file A.class.php
class A {
public function doSomething[]{
//doing something.
}
}
and a second class named B on another file B.class.php
require_once 'A.class.php';
class B {
//Call the method doSomething[] from the class A.
}
I think now it's clearn. How to : Call the method doSomething[] from the class A ?
asked Oct 10, 2012 at 18:38
Class B will need an object of Class A to call the method on:
class B {
public function doStuff[] {
$a = new A[];
$a->doSomething[];
}
}
Alternatively, you can create the instance of A outside of B and pass it into B's constructor to create a global reference to it [or pass it to an individual method, your choice]:
class B {
private $a = null;
public function __construct[$a] {
$this->a = $a;
}
public function doStuff[] {
$this->a->doSomething[];
}
}
$a = new A[];
$b = new B[$a];
answered Oct 10, 2012 at 18:40
newfurnitureynewfurniturey
36.3k9 gold badges91 silver badges101 bronze badges
5
How about injecting class A into B, making B dependant on A. This is the most primitive form of dependency injection:
class A
{
public function doSomething[]
{
//doing something.
}
}
class B
{
private $a;
public function __construct[ A $a ]
{
$this->a = $a;
}
//Call the method doSomething[] from the class A.
public function SomeFunction[]
{
$this->a->doSomething[];
}
}
This is constructed like this:
$a = new A[];
$b = new B[ $a ];
answered Oct 10, 2012 at 18:42
JvdBergJvdBerg
21.6k8 gold badges35 silver badges54 bronze badges
You need to instantiate a an object of class A. You can only do this inside a method of class B.
class B{
public function doSomethingWithA[]{
$a = new A[];
return $a->doSomething[];
}
}
answered Oct 10, 2012 at 18:39
RayRay
38.8k19 gold badges91 silver badges132 bronze badges
class B {
public function __construct[]
{
$a = new A;
$a->doSomething[];
}
}
answered Oct 10, 2012 at 18:40
wessidewesside
5,5205 gold badges28 silver badges35 bronze badges
I know this is an old question but considering I found it today I figured I'd add something to @newfurniturey's answer.
If you wish to retain access to class B within class A this is what I did:
class A
{
private $b = null
public function __construct[]
{
$this->b = new B[$this];
if [!is_object[$this->b] {
$this->throwError['No B'];
}
$this->doSomething[];
}
public function doSomething[] {
$this->b->doStuff[];
}
private function throwError[$msg = false] {
if [!$msg] { die['Error']; }
die[$msg];
}
}
class B {
public function doStuff[] {
// do stuff
}
}
This is constructed like this:
$a = new A[];
answered Nov 28, 2014 at 12:42
zanderwarzanderwar
2,6233 gold badges19 silver badges42 bronze badges