Advertisement
Yousuf1791

Book-page-99

Jun 12th, 2022
1,132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.11 KB | None | 0 0
  1. <?php
  2.  
  3. class Post{
  4.     private $post = "";
  5.  
  6.     public function __construct($post){
  7.         $this->post = $post;
  8.     }
  9.  
  10.     public function showPost(){
  11.         echo $this->post. "<br>";
  12.     }
  13. }
  14.  
  15. class User{
  16.     private $name = "";
  17.     private $posts = [];
  18.  
  19.     public function __construct($name){
  20.         $this->name = $name;
  21.     }
  22.  
  23.     public function showName (){
  24.         echo "Last post from ". $this->name .": <br>";
  25.     }
  26.  
  27.     private function readPosts(){
  28.         //reset array
  29.         unset($this->posts);
  30.         //get post list
  31.         $this->posts[] = new Post("Sample post 1");
  32.         $this->posts[] = new Post("Sample post 2");
  33.         $this->posts[] = new Post("Sample post 3");
  34.     }
  35.  
  36.     public function getPosts(){
  37.         //read posts
  38.         $this->readPosts();
  39.         //return posts array
  40.         return $this->posts;
  41.     }
  42.  
  43.     public function getLastPosts(){
  44.         //read posts
  45.         $this->readPosts();
  46.         $count = count($this->posts);
  47.         if ($count > 0) {
  48.             return $this->posts[$count-1];
  49.         }else{
  50.             return NULL;
  51.         }
  52.     }
  53.  
  54. }
  55.  
  56. $user = new User("Niton");
  57. $user->showName();
  58.  
  59. //get user last post
  60. $last_post = $user->getLastPosts();
  61. if ($last_post != null) {
  62.     $last_post->showPost();
  63. }
  64.  
  65. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement