I'm still learning OOP so this might not even be possible (although I would be surprised if so), I need some help calling another classes method.
For example in ClassA I
have this method:
function getName()
{
return $this->name;
}
now from ClassB
(different file, but in the same directory), I want to call ClassA
's getName()
, how do I do that? I tried to just do an include()
but that does not work.
Thanks!
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
Without inheritance or an instance method, you'd need ClassA to have a static method
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
--- other file ---
Regardless of the solution you choose,
require 'ClassA.php
is needed.If they are separate classes you can do something like the following:
What I have done in this example is first create a new instance of the
A
class. And after that I have created a new instance of theB
class to which I pass the instance ofA
into the constructor. NowB
can access all the public members of theA
class using$this->a
.Also note that I don't instantiate the
A
class inside theB
class because that would mean I tighly couple the two classes. This makes it hard to:B
classA
class for another classFile 1
File 2