PHP Class Exercises : Display a string
PHP class: Exercise-1 with Solution
Write a simple PHP class which displays the following string.
'MyClass class has initialized !'
Sample Solution:
PHP Code:
<?php
class MyClass {
// Define a class named MyClass
class MyClass {
// Define a constructor method
public function __construct()
{
// Output a message indicating that the class has been initialized
echo 'MyClass class has initialized !'."\n";
}
}
// Create an instance of the MyClass class
$userclass = new MyClass;
?>
Output:
MyClass class has initialized !
Explanation:
In the exercise above,
- class MyClass {: This line defines a class named "MyClass".
- public function __construct() {: This line defines a constructor method for the "MyClass" class. The constructor method is automatically called when an object of the class is created.
- echo 'MyClass class has initialized !'."\n";: This line outputs a message indicating that the class has been initialized.
- $userclass = new MyClass;: This line creates an instance of the "MyClass" class, which triggers the execution of the constructor method and outputs the initialization message.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: PHP Classes Exercises Home.
Next: 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.
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