Ryan Ryan - 5 months ago 9
PHP Question

PHP: Calling another class' method

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!

Answer
//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>
Comments