【问题标题】:How can i calling a function within a Class method如何在 Class 方法中调用函数
【发布时间】:2017-11-14 18:20:03
【问题描述】:

我想在类方法中调用一个函数,我创建了这个脚本,但不能正常工作?

致命错误:在第 12 行的 /.../.../index.php 中,在 null 上调用成员函数 function2()

    public static function table($name_t, callable  $callback){
    self::databaseConnection();
    try {

        $matches = array(
            .....
        );


        function engine($var){
            Gaia::$engine__ = $var[0];
        }

        $eng = new Table_call;
        echo $eng;


        $callback($matches);

        if(isset(self::$s)){
            //self::$instance->exec("CREATE TABLE IF NOT EXISTS ".$name_t."( ".trim(self::$s,',')." ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

            echo "Dump Success!<br> ".self::$engine__ ;
        }

        //return $bgj;
    } catch (Exception $e) {
        self::$instance = null; 
        echo ("Oh noes! There's an error in the query: ". $e);
    }

}

类文件 2

class Table_call extends Gaia{

     public function __call($name,$arg){
      call_user_func($name,$arg);
     }
 }

索引文件

Gaia::table('test', function($table){
   $table['autoIncrement']('id');
})->engine('MyISAM');

我怎样才能以这种方式添加功能??

" ->function2('hello') "?

【问题讨论】:

  • 静态函数需要通过::请求,而非静态函数需要通过$this-&gt;请求。因此,在您的情况下,它将是self::function();,如果您将其设为非静态函数,它将是$this-&gt;function();。这会帮助你吗?一些额外的解释:stackoverflow.com/questions/1417438/…
  • 你能把整个 html 代码贴在你尝试回显 php 代码的地方吗?
  • 好的抱歉,更新了。
  • 你没有在方法中返回任何东西。通常,链接需要返回。
  • 相关? Chaining Static Methods in PHP?(可能是骗子)

标签: php


【解决方案1】:

我不知道这是否是你想要的,但这是我能做的最小的例子。在您的问题中,我不清楚您到底要做什么,因为您发布的任何代码中都没有function2,所以我必须猜测那是什么。总之……

<?php
class Gaia{
    public static function table(){
        return new Table_call();
    }
}

class Table_call extends Gaia{

    public function function2(){
        echo __METHOD__;
    }

}

Gaia::table()->function2();

你可以在这里试试。

http://sandbox.onlinephpfunctions.com/code/dd1c5db302448e8f075a081acfc33cb00c3f71b5

查看您的代码,您没有返回任何对象来调用第二个函数。这样想吧

$var =  Gaia::table();
 //var is an instance of Table_call
$var->function2();

也是你的错误

致命错误:在第 12 行的 /.../.../index.php 中,在 null 上调用成员函数 function2()

默认返回类型是NULL 所以...

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 2016-03-28
    • 2018-02-06
    • 2014-12-12
    • 2013-07-08
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多