PHP Class Exercises: An introductory message as an argument value of the method within the class
Write a simple PHP class which displays an introductory message like "Hello All, I am Scott", where "Scott" is an argument value of the method within the class.
Sample Solution:
PHP Code:
<?php
// Define a class named user_message
class user_message {
// Define a public property named $message and initialize it with a default value
public $message = 'Hello All, I am ';
// Define a method named introduce which accepts a parameter $name
public function introduce($name)
{
// Concatenate the message with the provided name and return the result
return $this->message.$name;
}
}
// Create an instance of the user_message class
$mymessage = new user_message();
// Call the introduce method of the $mymessage object and output the result
echo $mymessage->introduce('Scott')."\n";
?>
Output:
Hello All, I am Scott
Explanation:
In the exercise above,
- class user_message {: This line defines a class named "user_message".
- public $message = 'Hello All, I am ';: This line defines a public property named '$message' and initializes it with the string value 'Hello All, I am '.
- public function introduce($name) {: This line defines a public method named "introduce()" which accepts a parameter '$name'.
- return $this->message.$name;: This line concatenates the value of the '$message' property with the provided '$name' parameter and returns the resulting string.
- $mymessage = new user_message();: This line creates an instance of the user_message class.
- echo $mymessage->introduce('Scott')."\n";: This line calls the "introduce()" method of the "$mymessage" object, passing the string 'Scott' as an argument, and outputs the returned string followed by a newline character.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a simple PHP class which displays the specified string.
Next: Write a PHP class that calculates the factorial of an integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics