2016-10-04 52 views
0

嗨,我只是學習PHP,我正在嘗試各種代碼示例/練習。下面是一個PHP - 語言新手

<?php 
// class definition 
class Bear 
    { 
    // define properties 

    public $name; 
    public $weight; 
    public $age; 
    public $colour; 
    public $sex; 

    // constructor 
    public function _construct() 
     { 
      $this->age = 0; 
      $this->weight = 100; 
      $this->colour = "Brown"; 
      }  
    } 

    // create instance 

    $baby = new Bear; 
    $baby->name = "Baby bear"; 
    $sex->sex = "Male";  

    echo $baby->name." is ".$baby->colour." and weighs ".$baby->weight." units at birth and his sex is ".$baby->sex; 
?> 

當我運行這個文件,它返回

寶寶熊和出生時體重的單位和他的性是

它不拿起變量。 任何建議都會很棒。 謝謝

+2

'$性別> sex'是什麼呢?'$愛嬰>性別'應該是'$ sex-> sex'或者這個'$ sex-> sex'應該是'$ baby-> sex' ... – devpro

+8

'_construct()'應該是'__construct()'(2個下劃線);年齡,顏色和重量不在構造函數中設置,因爲它不是構造函數。 – CD001

+0

感謝所有幫助工作現在好了 – Mike

回答

4

該程序是非常簡單,它並不複雜。這裏的問題是

1)構造一個構造函數的方式,你創建了一個類Bear。使構造函數代碼中的

public Bear() { //Your code here } //Deprecated in PHP7 
       or 
public function __construct() 

2)您創建了一個名爲$嬰兒和$性實例是該對象的變量。但是你寫了

$sex->sex = "Male"; //This is wrong as $sex is a variable not an object 
$baby->sex = "Male"; //Correct way of representation 

在你的代碼中做這些改變,它肯定會起作用。

希望這可以幫助你。

+3

使用類名作爲構造函數的名稱在PHP7中被棄用......更好地使用'__construct()' – CD001

+1

我認爲在他提到的問題中使用了雙下劃線,這就是爲什麼我建議他使用基本構造函數。但是現在我觀察到他使用了單音下劃線。如果他使用PHP7,使用__construct()是最好的選擇,否則任何事情都是一樣的。感謝您的更正。 –

+1

謝謝,改變它的方式你推薦,它的工作 – Mike

1

PHP中的構造函數需要下劃線,你只有一個在你的原代碼。這裏是你的代碼與正確聲明的構造函數:

<?php 
// class definition 
class Bear 
{ 
// define properties 

public $name; 
public $weight; 
public $age; 
public $colour; 
public $sex; 

// constructor 
public function __construct() 
    { 
     $this->age = 0; 
     $this->weight = 100; 
     $this->colour = "Brown"; 
     }  
} 

// create instance 

$baby = new Bear; 
$baby->name = "Baby bear"; 
$baby->sex = "Male";  

echo $baby->name." is ".$baby->colour." and weighs ".$baby->weight." units at birth and his sex is ".$baby->sex; 
?> 
+0

評論應作爲評論發佈而不是答案。你做了什麼改變,爲什麼?它不寫在那裏? –

+0

感謝您的幫助,現在工作 – Mike

+0

*「試試」* - 爲什麼? –

0

你缺少的構造下劃線,它應該是

public function __construct() {} 

還行$sex->sex = "Male";應該$baby->sex = "Male";

+0

感謝您的建議 – Mike