0

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 writer() {
        if() {
            // if true
        } else {
            // call function hello
        }
    }

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

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

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the very quick feedback, may I ask is this the best approach?
Yes, it's pretty much the only approach, unless you're using the class statically, in that case refer to the example in my updated post, otherwise $this is the best way to access functions inside the same class.
Very enlightening in just a matter of minutes, huge thanks Nexerus.
0
// call function hello
$this->hello();

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

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.