2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: PHP - Class
|
|
|
|
---
|
|
|
|
|
|
|
|
### Simple Class for Beginner!
|
|
|
|
|
|
|
|
```php
|
2018-11-19 14:56:38 +01:00
|
|
|
class Lab { // class keyword is mandatory identifier for class creation, after class keyword goes the name of the class(e.g. Lab)
|
|
|
|
private $name = ''; // $name is instance variable, which means that every instantiated object has it's own copy of variable $name
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2018-11-19 14:56:38 +01:00
|
|
|
public function setName($name) { // function setName is setter function that sets the value of instance variable $name
|
|
|
|
$this->name = $name; // because $name is the name of both instance variable and function parameter, we use $this keyword
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2018-11-19 14:56:38 +01:00
|
|
|
private function getName() { // getName is getter function that returns the value of instance variable $name
|
2018-10-12 15:37:13 -04:00
|
|
|
return $this->name;
|
|
|
|
}
|
|
|
|
|
2019-02-25 00:41:44 +07:00
|
|
|
public function sayMyName() {
|
2018-10-12 15:37:13 -04:00
|
|
|
$name = $this->getName();
|
|
|
|
return $name;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2019-02-25 00:41:44 +07:00
|
|
|
$breakingBad = 'Heisenberg';
|
|
|
|
$lab = new Lab();
|
|
|
|
$lab->setName($breakingBad);
|
|
|
|
echo "My Name is " . $lab->sayMyName(). "!";
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2018-11-21 22:50:18 +01:00
|
|
|
|
|
|
|
|
|
|
|
**Note**:
|
|
|
|
The keywords *private* and *public* define the visibility of the property or the method.
|
|
|
|
|
|
|
|
- Class members declared public can be accessed everywhere.
|
|
|
|
- Members declared as private may only be accessed by the class that defines the member.
|
|
|
|
|
|
|
|
### More Information
|
|
|
|
[visibility documentation](http://php.net/manual/en/language.oop5.visibility.php)
|