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();

 

 

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();
?>

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.