1

While I was trying to translate my website I came across a problem. I first used to translate something from an array with many keys but now I want to do it with a function.

So here is my code which obviously doesn't work:

class Foo extends Database {
   private $crumb = 'Hello';

   public function breadcrumb( callable $translate ) {
       return $translate($this->crumb);
       // So: $bar->translate($this->crumb);
   }
}

class Bar extends Database {
   private $translation = ['Hello'=>'Hallo']; // Array made out of words comming from a database

   public function translate($word) {
      return $this->translation[$word];
   }
}

On a page:

<?php
$foo = new Foo();
$bar = new Bar();
?>
<h1><? echo $foo->breadcrumb($bar->translate()); ?></h1> <!-- Expected result <h1>Hallo</h1> --> 

As you can see I have the classes already extended by another class so extending Foo with Bar isn't possible. So my problem is how can I call a method inside another class's method? I have this problem in a couple of other classes too.

I found a few things like below but still didn't help me.

Community
  • 1
  • 1
SuperDJ
  • 7,488
  • 11
  • 40
  • 74
  • For clarity: You wrote: "So my problem is how can I call a method inside another class's method?" Do I undertsand that you want to call a method in another class's METHOD? I think you mean you want to call a method in another class, right? – Erwin Moller Jul 13 '15 at 13:29
  • @ErwinMoller I guess so – SuperDJ Jul 13 '15 at 13:40

1 Answers1

1

http://docs.php.net/manual/en/language.types.callable.php says:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
<?php
class Foo /* extends Database */ {
   private $crumb = 'Hello';

   public function breadcrumb( callable $translate ) {
       return $translate($this->crumb);
   }
}

class Bar /* extends Database */ {
   private $translation = ['Hello'=>'Hallo'];

   public function translate($word) {
      return $this->translation[$word];
   }
}

$foo = new Foo;
$bar = new Bar;
echo $foo->breadcrumb( [$bar, 'translate'] ); ?>

(you also forgot the $this-> reference for accessing the instance memeber translation.)

VolkerK
  • 95,432
  • 20
  • 163
  • 226