Jump to content

Calling Class Function From Another Class


mikedag

Recommended Posts

Hi,

 

I am trying to get a grasp on OOP and am struggling to figure somethings out...

 

Say I have 3 files, class1.php, class2.php and index.php

 

If I call class2 from class1 and then only call class1 in index... is it possible to execute functions from class2 in the index file? example... (this obviously does not work!)

 

class class1 {
  function __construct () {
$class2 = new class2();
   }
}

class class2 extends class1 {
  function somefunction () {
echo "blah";
   }
}

 

Then in the index file:

include 'class1.php';
$class1 = new class1 (); 

$class1->class2->somefunction();

 

 

Link to comment
Share on other sites

Your problem is a scope issue. $class2 isn't a property of class1, it's just a variable who is only available in the scope of class1's constructer. You'd need to do it like this:

<?php
class class1
{
public $class2;

public function __construct()
{
	$this->class2 = new class2();
}
}

class class2
{	
public function test()
{
	echo 'Hello world!';
}
}

$class1 = new class1();
$class1->class2->test();
?>

Link to comment
Share on other sites

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.