PHP __construct()锛氭瀯閫犲嚱鏁/鏂规硶

2021 年 9 月 26 日1580

鏋勯犲嚱鏁帮紙constructor method锛屼篃绉颁负鏋勯犲櫒锛夋槸绫讳腑鐨勪竴绉嶇壒娈婂嚱鏁帮紝褰撲娇鐢 new 鍏抽敭瀛楀疄渚嬪寲涓涓瀵硅薄鏃讹紝鏋勯犲嚱鏁板皢浼氳嚜鍔ㄨ皟鐢ㄣ

鍦 PHP3.0 鍜 PHP4.0 涓锛屾瀯閫犲嚱鏁版槸涓涓涓庡叾鎵鍦ㄧ被鍚屽悕鐨勫嚱鏁般傝屽湪 PHP5 涓锛岃櫧鐒朵篃鏀鎸 PHP3.0 鍜 PHP4.0 涓鐨勭敤娉曪紝浣嗘槸鏇存帹鑽愪娇鐢__construct浣滀负绫荤殑鏋勯犲嚱鏁帮紝杩欐牱鍋氱殑濂藉勫氨鏄鏋勯犲嚱鏁版棤闇闅忕潃绫诲悕鐨勬敼鍙樿屽仛鍑轰慨鏀广傚湪 PHP7.0 涓搴熷純浜 PHP3.0 鍜 PHP4.0 涓鐨勭敤娉曪紝鏋勯犲嚱鏁板繀椤讳娇鐢 __construct 鏉ュ畾涔夈

鏋勯犲嚱鏁板氨鏄褰撳硅薄琚鍒涘缓鏃讹紝绫讳腑琚鑷鍔ㄨ皟鐢ㄧ殑绗涓涓鍑芥暟锛屽苟涓斾竴涓绫讳腑鍙鑳藉瓨鍦ㄤ竴涓鏋勯犲嚱鏁般傚拰鏅閫氬嚱鏁扮被浼兼瀯閫犲嚱鏁颁篃鍙浠ュ甫鏈夊弬鏁帮紝濡傛灉鏋勯犲嚱鏁版湁鍙傛暟鐨勮瘽锛岄偅涔堝湪瀹炰緥鍖栦篃闇瑕佷紶鍏ュ瑰簲鐨勫弬鏁帮紝渚嬪 new Students($name, $age)

鍒涘缓鏋勯犲嚱鏁扮殑璇娉曟牸寮忓備笅锛

public function __construct(鍙傛暟鍒楄〃){

... ...

}

鍏朵腑锛屽弬鏁板垪琛ㄦ槸鍙閫夌殑锛屼笉闇瑕佹椂鍙浠ョ渷鐣ャ

濡傛灉娌℃湁鍦ㄤ唬鐮佷腑鏄惧紡鍦板0鏄庢瀯閫犲嚱鏁帮紝绫讳腑浼氶粯璁ゅ瓨鍦ㄤ竴涓娌℃湁鍙傛暟鍒楄〃骞朵笖鍐呭逛负绌虹殑鏋勯犲嚱鏁般傚傛灉鏄惧紡鍦板0鏄庢瀯閫犲嚱鏁板垯绫讳腑鐨勯粯璁ゆ瀯閫犳柟娉曞皢涓嶄細瀛樺湪銆傛墍浠ユ瀯閫犲嚱鏁伴氬父鐢ㄦ潵鍋氫竴浜涘噯澶囧伐浣滐紝姣斿備负鏌愪簺鍙傛暟璧嬪肩瓑銆

娉ㄦ剰锛氬傛灉鏄惧紡鍦板0鏄庢瀯閫犲嚱鏁帮紝閭d箞瀹冪殑璁块棶鏉冮檺蹇呴』鏄 public锛岃屼笖鏋勯犲嚱鏁版槸鍦ㄥ疄渚嬪寲鏃惰嚜鍔ㄨ皟鐢ㄧ殑锛屾垜浠涓嶉渶瑕佹墜鍔ㄨ皟鐢ㄣ

銆愮ず渚嬨戝垱寤轰竴涓绫伙紝骞朵负鍏舵樉绀虹殑鍒涘缓鏋勯犲嚱鏁帮紝浠g爜濡備笅锛





<?php



class Website{



public $name, $url, $title;



public function __construct($str1, $str2, $str3){



$this -> name = $str1;



$this -> url = $str2;



$this -> title = $str3;



$this -> demo();



}



public function demo(){



echo $this -> name.'<br>';



echo $this -> url.'<br>';



echo $this -> title.'<br>';



}



}







$object = new Website('C璇瑷涓鏂囩綉','http://http://www.zjjv.com///php/','鏋勯犲嚱鏁');



?>

杩愯岀粨鏋滃備笅锛

C璇瑷涓鏂囩綉

http://http://www.zjjv.com///php/

鏋勯犲嚱鏁

浠g爜涓鎴戜滑鐢ㄥ埌浜 $this锛屽畠琛ㄧず褰撳墠璋冪敤鐨勫硅薄锛岃屼笖 $this 鍙鑳藉湪绫荤殑鏂规硶涓浣跨敤锛屾洿澶氬叧浜 $this 鐨勭煡璇嗗悗闈㈡垜浠浼氳︾粏浠嬬粛銆

0 0