How to make a class in PHP
How to make a class in PHP
1 Answer
A class is a place that contains a set of codes about a specific topic.
I will show you how to write a User class in PHP
Create an index.php file.
Then write your class.
The class starts with the class keyword followed by a class name example 'User'.
<?php
class User {
}
?>
after that, you can add the property and method of your class.
I will add 2 property (name and email ) and 3 method (setUserData(), getUserName(), getUserEmail()).
<?php
class User {
public $name;
public $email;
public function setUserData($name,$email){
$this->name = $name;
$this->email = $email;
}
public function getUserName(){
return $this->name;
}
public function getUserEmail(){
return $this->email;
}
}
?>
now you can make-instance and use the User class
<?php
class User {
public $name;
public $email;
public function setUserData($name,$email){
$this->name = $name;
$this->email = $email;
}
public function getUserName(){
return $this->name;
}
public function getUserEmail(){
return $this->email;
}
}
$user = new User();
$user->setUserData('ahmad', 'ahmad@gmail.com');
echo $user->getUserName().' '.$user->getUserEmail();
?>
answer Link