Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.