开发者

call a function from inside a function php oop

I wonder if this is possible, although I'm quite convince maybe there is a better approach for this. I have this script structure:

class Mother {
    public function __construct() {
        // script here
    }

    public function wri开发者_开发百科ter() {
        if() {
            // if true
        } else {
            // call function hello
        }
    }

    public function hello() {
        echo "Hello there.";
    }
}

How can I call hello() from writer()? Thanks.


Like so

public function writer() {
    $this->hello();
}

$this is a reserved variable for classes, any class that is instantiated (called via new myClass) has access to $this, however if you're using a static class, you would need to define that function as static and use the static::myFunction approach, for example:

class exampleClass {
    public static function exampleFunc() {
        static::hello();
    }
    public static function hello() {
        echo "Hello!";
    }
}
exampleClass::exampleFunc();


// call function hello
$this->hello();

Also, your other functions are syntactically wrong. Note the parenthesis.

public function writer() {
public function hello() {


on my PHP 5.3.4 installation

public function hello() { }

seems to to available from another instance method in two ways

$this->hello()
self::hello()

Obviously,

$this

the reference to the instance will not be available when calling a public method as a class method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜