Setters and Getters in PHP

So one of the stuff that I like to do in Java is basically work with Objects. some OOP. You learn Structure, atleast I am just used to see code as follows:


  ` class Name {
// private Properties 
// Here put your setters and getters
// Here put your Functions
// Remember to put your constructors with your functions. 
// every company is different I like putting properties then functions // and the constructor is a function it self too. 
}

I found this piece of code on Gitghub and I am bringing up because it is clean code. Here is the link: https://github.com/iamshaunjp/object-oriented-php/blob/lesson-6/index.php

<?php 

  class User {

    public $username;
    private $email;

    public function __construct($username, $email){
      //$this->username = 'ken';
      $this->username = $username;
      $this->email = $email;
    }

    public function addFriend(){
      //return "added a new friend";
      return "$this->username just added a new friend";
    }

    // getters
    public function getEmail(){
      return $this->email;
    }

    // setters
    public function setEmail($username){
      if(strpos($username, '@') > -1){
        $this->email = $username;
      };
    }

  }

  $userOne = new User('mario', '[email protected]');
  $userTwo = new User('luigi', '[email protected]');

  echo $userOne->getEmail() . '<br>';
  echo $userTwo->getEmail() . '<br>';
  
  $userTwo->setEmail('[email protected]');
  
  echo $userTwo->getEmail() . '<br>';

?>

<html lang="en">
<head>
  <title>PHP OOP</title>
</head>
<body>
  
</body>
</html>

In the example above you can see how the functions are used and how everything is set. it is a lot happening actually in the piece of code. Here is a link in YouTube with the Net Ninja Explaining.

This is all for now! I like PHP.

Talk to you later and Code!!

Very Respectfully

Santi

Categories: php