将参数传递给其他类方法

时间:2015-07-13 13:16:55

标签: php

当我试图翻译我的网站时,我遇到了一个问题。 我首先习惯使用许多键从数组中翻译某些内容,但现在我想用函数进行翻译。

所以这是我的代码显然不起作用:

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];
   }
}

在页面上:

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

正如您所看到的,我已经将类扩展为另一个类,因此无法使用Foo扩展Bar。 所以我的问题是如何在另一个类的方法中调用一个方法?我在其他几个课程中也有这个问题。

我发现了一些像下面这样的东西,但仍然没有帮助我。

1 个答案:

答案 0 :(得分:1)

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

实例化对象的方法作为包含索引为0的对象和索引为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'] ); ?>

(您还忘记了访问实例memeber translation的$ this-&gt;参考。)