Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class property from outside of class

Tags:

oop

php

Suppose I had the following class:

class MyClass {
    public function Talk() {
        $Say = "Something";
        return $Say;
    }
}

I then started an instance of the class:

$Inst = new MyClass();

How can I now call $Say outside MyClass hence, for example, echo it on the document? For example, having something like:

$Said = "He" . $Say
like image 218
max0005 Avatar asked Oct 16 '25 04:10

max0005


2 Answers

I strongly recommend you read through http://php.net/manual/en/language.oop5.php. It will teach you the fundamentals of OOP in PHP.


In your example, $Say is just another variable declared within Talk()'s scope. It is not a class property.

To make it a class property:

class MyClass {
    public $say = 'Something';

    public function Talk() {
        return $this->say;
    }
}

$inst = new MyClass();
$said = 'He ' . $inst->say;

That defeats the purpose of Talk() however.
The last line ought to be $said = 'He '. $inst->Talk();

like image 179
simshaun Avatar answered Oct 18 '25 17:10

simshaun


$say is not a class property. If it was, you would define your class like this:

class MyClass {
    public $say;      
}

It is instead a local variable of the function Talk(). If you want to access it the way that you have the class defined, you would do:

$instance = new MyClass();
$instance->Talk();
like image 20
Jeff Lambert Avatar answered Oct 18 '25 16:10

Jeff Lambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!