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
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();
$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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With