Jump to content

calling a class method from another class


RoyHB

Recommended Posts

A main program creates instances of 2 classes.

 

I'd like to be able to call a method in class1 from within class 2.

I'd like to use a public method within the instance of class 1 that was created in the main program rather than recreating class1 within class2

 

first experiment that I tried the public method within class1 was not visible to class 2

 

class 2 will only ever be used if class 1 has been previously loaded.

Can this be made to work?

 

Thanks

 

skeletal example:

<?php
     $firstClass = new class1();
     $secondClass = new class2();
     $secondClass->doSomething();
?>

<?php
     class class1 {
          public function someFunction() {
               ...do some stuff
          }
     }
?>          

 

<?php
     class class2 {
          function doSomething() {
               $firstClass->someFunction();
          }
     }
?>

You want to do something like this

 

<?php
     class class2 {
          function doSomething( class1 $firstClass ) {
               $firstClass->someFunction();
          }
     }
?>

 

Then

 

<?php
     $firstClass = new class1();
     $secondClass = new class2();
     $secondClass->doSomething( $firstClass );
?>

You could also just simply inheritate the class2 from the class1 to use class1's functions inside class2.

 

class Class1
{
function test1()
{
	echo 'Function from class1<br>';
}
}

class Class2 extends class1
{
function test2()
{
	echo 'Fcuntion from class2<br>';
}
}

$obj = new Class2();
$obj->test1(); // Function from class1
$obj->test2(); // Fcuntion from class2

You could also just simply inheritate the class2 from the class1 to use class1's functions inside class2.

 

why not make class2 extend class 1, then use parent::

 

We don't know what each class does since the OP did not give any concrete code. So it's best to advice composition over inheritance IMO.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.