Jump to content

Calling A Method In A Class From Another Class


programming.name

Recommended Posts

Hi,

 

Is there an acceptable way to call a method in a class from another class?

 

I have 3 files and 2 classes as below:

 

 

a.php

 

class a

{

function func_a()

{

b::func_b //it is a place where I want to call func_b() and this give me an error

}

}

 

b.php

class b

{

function func_b()

{

echo 'I got in!';

}

}

 

c.php

 

<?php

include("a.php")// or require_once

include("b.php")// or require_once

$a = new a;

$b = new b;

?>

<html>

<head>

</head>

<body>

<?php

$a->func_a(); //I got in! to the display

?>

</body>

</html>

 

I tried:

 

b::func_b

 

in func_a in class a, it gives the following error:

Strict standards: Non-static method b::func_b() should not be called statically, assuming $this from incompatible context in a.class.php on line 12

 

I can hide thie error using:

error_reporting(E_ALL ^ E_STRICT);

 

This is not what I want; I want some "clean code".

Is there a way to achieve this?

 

Thanks in advance.

class AnObject {
  private $anotherObject;
  public function __construct(AnotherObject $B) {
    $this->setAnotherObject($B);
  }
  public function setAnotherObject(AnotherObject $B) {
    $this->anotherObject = $B;
  }
  public function showAnotherObject() {
    $this->anotherObject->show();
  }
}
class AnotherObject {
  public function show() {
    echo 'I got in!';
  }
}
$a = new AnObject(new AnotherObject);
$a->showAnotherObject();

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.