Arrow operator in PHP
Aug 29, 2020
PHP
Beginner
Programming Study Diary
#Programming study diary
August 29, 2020
Summarize how to use the arrow operator (->
symbol).
What is the #Arrow operator?
As mentioned above, the ->
symbol is called the arrow operator. The arrow operator specifies the instance of the class on the left side and the property or method of the class on the left side on the right side, and calls the access method to the property.
#How to write The usage example of the arrow operator is as follows.
// Access the property name that is the property of the instance
$instance-> property;
// Call a method that is a method of the instance
$instance->method();
Specifically, in the following example, the variable “$basketball” in the class “sports” is accessed and the value is fetched.
class Sports {
$basketball = "basketball"
$baseball = "baseball"
$soccer = "football"
}
fruit->$basketball // baseball
Retrieve date using #DataTime class ▽ Retrieve the date from the DataTime class as a predetermined format. Date and time and time zone are stored in DataTime class.
// Get the current date and time with DateTime class and store it in a variable
$date = new DateTime();
// output the date and time from that variable using format
echo $date->format('Y year m month d day');
// output result
// August 29, 2020
#Concrete example
❖ Summarize how to use the arrow operator by specifying the class name, property name, method name, processing within the method, etc.
Define a sports class Sports
that has name
as a property and introduceSports
as a method.
// sports class
class Sports {
// name
$name;
// set the name when creating an instance in the constructor
function __construct($name) {
$this->name = $name;
}
// Introduce your favorite sport
function introduceSports() {
echo "My favorite sport is ". $this->name ."". PHP_EOL;
}
}
// Create an instance of the sports class whose name is "basketball"
$basketball = new Sports("basketball");
// Access the name and confirm
echo $basketball->$name.PHP_EOL; // basketball
// Call the method of introduction
$basketball->instoduceSports(); // my favorite sport is basketball
References
How to use arrow operator in PHP [for beginners] Easy-to-understand PHP arrow operator (->)