最佳实践:如何在PHP中创建一个好的课程

时间:2016-03-11 09:36:20

标签: php class

  1. 我想改进我的php web开发,所以,我想知道当你创建一个新的对象类时你最好的实践是什么?

  2. 我有一个类对象的示例。我想知道你是怎么做到的。如果它的好坏。

  3.   Class Contact extends Object {
    
        public $id;
    
        public $firstname = 'john';
    
        public $lastname = 'doe';
    
        public function __construct($id_contact = NULL) {
    
                parent::__construct($id_contact);
    
    
            if ($this->id) {
    
                    $this->fullname = $this->firstname . ' '.$this->lastname
                }
            }
            public static function getFullName($id_contact){
    
                $cnt = new Contact($id_contact);
                return $cnt->fullname;
            }
    
            }
    

    在不同的控制器中使用这样的方法:

    $cnt_fullname = Contact::getFullName($id);
    

    或者在控制器中加载新对象

    更好
    $cnt = new Contact($id);
    $cnt_fullname = $cnt->fullname;
    

    感谢您的回复。

2 个答案:

答案 0 :(得分:1)

我上课的方式:

name

答案 1 :(得分:0)

所以,例如最佳方式

    class Getter {

       private static $contact = null   

       public static function getContactObj($id) {
          if(!is_null(self::$contact)) {
             return self::$contact;
          }
          self::$contact = new Contact($id);
          return self::$contact;
       }
    }

和您的班级联系

    Class Contact extends Object {

        public $id;

        public $firstname = 'john';

        public $lastname = 'doe';


        public function setId($id) {
            $this->id = $id;
            return $this;
        }

        public function getFullName()
            $this->fullname = $this->firstname . ' '.$this->lastname
            return $this->fullname;
        }

  }

你可以在过度控制器中使用这种结构:

Getter::getContactObj()
        ->setId(1)
        ->getFullName();

Getter::getContactObj()
        ->setId(2)
        ->getFullName();

Getter::getContactObj()
        ->setId(3)
        ->getFullName();

等等。

相关问题