【问题标题】:How to call another class function in PHP如何在 PHP 中调用另一个类函数
【发布时间】:2013-01-29 06:41:59
【问题描述】:

我的问题类似于Call function in function from another class PHP,但它的答案对我不起作用。

基本上这就是我想要做的。

在'a.php'中,我定义了A类。

class A{
  function ab(){}
  function cd(){}
  function ef(){}
  ...
}

在'b.php'中,我想定义类B,可以调用类A中的函数。这是我放的,但它似乎不起作用。

class B{
  function xy(){
    require 'a.php';
    $a = new A();
    $this->x = $a->ab();
    $this->y = $a->cd();
    return $a->ef();
  }
}

谁能指出我正确的方向?谢谢

========

更新:为了让我的问题更清楚,我举了另一个例子。

class Person{
  function firstName(){return $this->firstName;}
  function lastName() {return $this->lastName;}
  function address()  {return $this->address;}
  ...
}

class Car{
  function ownerInfo(){
     $owner = array();
     require 'person.php';
     $p = new Person($this->ownerID);
     $owner['firstname'] = $p->firstName();
     $owner['lastname']  = $p->lastName();
     $owner['address']   = $p->address();
     //I am sure the data is there, but it returns nothing here
     return $owner;  
  }
}

【问题讨论】:

  • Inheritance?....只需将class B 扩展为class A 即可使用class A 中定义的那些方法
  • 用A类扩展B类
  • 不确定 php,但我知道在 c++ 中,您在标题中包含(需要)文件(以及文件的开头,或在 B 类减速之前)
  • 实际上 A 和 B 是不同的模型,所以我不想使用“B 类扩展 A”。 A 和 B 中的大多数其他功能是不相关的。
  • 我尝试将 require 语句放在文件的开头,但它也不起作用。

标签: php class function


【解决方案1】:

这样试试

class B extends A{
  function xy(){
    require 'a.php';
    $a = new A();
    $this->x = $a->ab();
    $this->y = $a->cd();
    return $a->ef();
  }
}

【讨论】:

  • 当然它不好,但我们可以这样使用,因为它可能会在使用此类 B 时提取 a.php 文件,否则可能会减少加载无价值的 a.php..??
  • 还有其他方法吗?实际上我已经放了“A类扩展C”和“B类扩展D”
  • 添加extends A 没有任何作用。它只会增加代码混乱。
  • @coolmoon 你可以这样做,如果你将其他人扩展到其他人,就会有 NP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 2015-07-03
相关资源
最近更新 更多