【问题标题】:Pass method with argument to other class method将带参数的方法传递给其他类方法
【发布时间】:2015-10-01 18:46:40
【问题描述】:

当我试图翻译我的网站时,我遇到了一个问题。 我一开始是从一个有很多键的数组中翻译一些东西,但现在我想用一个函数来做。

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

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> --> 

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

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

【问题讨论】:

  • 为了清楚起见:您写道:“所以我的问题是如何在另一个类的方法中调用方法?”我知道你想在另一个类的 METHOD 中调用一个方法吗?我想你的意思是你想调用另一个类中的方法,对吧?
  • @ErwinMoller 我猜是的

标签: php


【解决方案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'] ); ?>

(您还忘记了用于访问实例成员 translation 的 $this-> 引用。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多