How can one access a variable from one class in another class in PHP using object-oriented programming?
To access a variable from one class in another class in PHP using object-oriented programming, you can create a public getter method in the class that contains the variable you want to access. This getter method will allow you to retrieve the value of the variable from an instance of that class in another class.
class Class1 {
public $variable = 'Hello';
public function getVariable() {
return $this->variable;
}
}
class Class2 {
public function accessVariableFromClass1(Class1 $class1) {
echo $class1->getVariable();
}
}
$class1 = new Class1();
$class2 = new Class2();
$class2->accessVariableFromClass1($class1);
Keywords
Related Questions
- Are quote(), quoteInto(), and quoteIdentifier() functions in PHP preferable over older methods like mysql_real_escape_string()?
- What is the best practice for uploading multiple images simultaneously in PHP?
- What are best practices for formatting log files in PHP to make them easily readable and manipulable?