Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Calling another class' method

Tags:

oop

php

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!

like image 700
Ryan Avatar asked Nov 21 '12 23:11

Ryan


People also ask

What is OOP PHP?

PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.


1 Answers

//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(); ?> 
like image 157
codingbiz Avatar answered Sep 22 '22 23:09

codingbiz