【问题标题】:Creating a class with methods within a class?用类中的方法创建一个类?
【发布时间】:2013-02-01 19:20:56
【问题描述】:

我想创建一个本身就是一个类的属性,并在“父”类MyName中添加其他方法,这样我就可以做类似的事情

$myname = new MyName();
$myname->event->post($params);

我尝试了以下方法,但它不起作用:

class MyName {
    public function __construct() {
        $this->event = new stdClass();
        $this->event->post = function($params) {
            print_r($params);
        };
    }
}

$x = new MyName();
$x->event->post(array(1, 2, 3));

最终会标记以下致命错误:

Fatal error: Call to undefined method stdClass::post() in C:\xampp\htdocs\Arkway\recreation\primepromotions\api\classes\FacebookWrapper.php on line 25

【问题讨论】:

  • 你忘记了new关键字
  • 抱歉,我在复制/粘贴代码后添加了它,但添加它仍然会产生显示的错误。

标签: object php stdclass


【解决方案1】:

您可以使用__call 访问内部闭包数组,可能是这样的:

class MyName {
  public function __construct() {
     $this->event = new EventObj();
     $this->event->post = function($params) {
          print_r($params);
      };
  }
}

class EventObj {

  private $events = array();

  public function __set($key, $val) {
    $this->events[$key] = $val;
  }

  public function __call($func, $params) {
     if (isset($this->events[$func])) {
       call_user_func_array($this->events[$func], $params);
     }
  }
}


$x = new MyName();
$x->event->post(array(1, 2, 3));

输出:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
)

【讨论】:

  • 已修复 - 为什么你这么关心我的回答?
  • 对不起,我的错。 +1,__set 的技巧甚至是更好的技术。如果您可以在没有call_user_func_array 的情况下提及how to use anonymous functions,那就太好了
【解决方案2】:

你不能在 PHP 中做到这一点。

您可以创建另一个类,然后在主类中对其进行初始化并通过变量访问它,或者如果您想将代码全部保存在一个对象中,您可以模拟方法链接。这篇文章http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html 展示了 PHP 中的一种方法链接方式。

【讨论】:

    【解决方案3】:

    你可以这样做:

    class MyName extends stdClass{
    

    class MyName {
        public function getStdClass(){
            return new StdClass();
        }
    

    您可以致电:

    $test = new MyName();
    $test->someStdClassMethod();
    

    $test = new MyName();
    $test2 = $test->getStdClass();
    $test2->someStdClassMethod();
    

    各自的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2019-07-29
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    相关资源
    最近更新 更多