【问题标题】:Calling a function from Class in another function在另一个函数中从 Class 调用一个函数
【发布时间】:2013-03-22 13:44:34
【问题描述】:

我想更好地了解函数调用在 OOP 中是如何工作的。我有以下示例:

class SomeClass {
    function __construct(){
        //run function do()
        //run function include()
        //run function run()
    }

    public function do($foo){
        //do some stuff
    }

    public function include(){
        require_once( CONSTANT . 'required.php' );
    }

    public function run(){
        required_func();
    }
}

$load_class = new SomeClass();

在required.php中:

function required_func(){

    $customerInfo = "info";
    $customer = $this -> do($customerInfo); //--> This isn't right
    return $customer;
}

我想要做的是让 required_func() 使用 $customerInfo 运行 do()。所以本质上:如何从 require_once 文件中包含的另一个函数调用一个类公共函数?我什至在这里遥遥无期?

感谢您的帮助

【问题讨论】:

  • 将 $this 在您的调用中传递给 required_func() 然后接受 $customerObject 作为 required_func() 中的参数并针对 $customerObject 调用 do()

标签: php oop


【解决方案1】:

$this 不在函数 required_func() 的范围内

class SomeClass {
    function __construct(){
        //run function do()
        //run function include()
        //run function run()
    }

    public function do($foo){
        //do some stuff
    }

    public function include(){
        require_once( CONSTANT . 'required.php' );
    }

    public function run(){
        required_func($this);
    }
}

$load_class = new SomeClass();

和

function required_func($customerObject){

    $customerInfo = "info";
    $customer = $customerObject->do($customerInfo);
    return $customer;
}

【讨论】:

  • 谢谢,它有效。所以本质上 $customerObject 传递给类的 $this?
  • 没关系 :) 刚刚看到您对这个问题的评论...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多