1.PHP裡的Object有

class Classname {

}

或是

$obj1 = new Classname();

此兩種方式建立,後者稱為constructor

第一種Object建立方式範例

class Classname {
  public $prop1 = true;
  public $prop2;
  public $prop3;
  public $prop4;
}
  $obj1 = new Classname();
  $obj2 = new Classname();
  echo $obj1->prop1;

 constructor亦可以用method(在class中的function)來運用

EX:

class Classname {
  public $prop1 = true;
  public $prop2;
  public $prop3;
  public $prop4;
  public  function functionName($prop2, $prop3, $prop4) {
    $this->prop2 = $prop2;
    $this->prop3 = $prop3;
    $this->prop4 = $prop4;
  }
}
  $obj1 = new Classname("tired", "54321", 54321);
  $obj2 = new Classname("your", "name", 99);
  echo $obj1->prop1;
  echo $obj2->prop4;

 

 2.__construct(){}

construct是PHP內建method,當新的Object以new來新增時會用到

EX:

<?php
class Dog{
public $numLegs = 4;
public $name;
public function __construct($name){
$this->name=$name;
}
public function bark(){
return "Woof!";

}
public function greet(){
return "Nice to meet you, ".$this->name."!";
}
}
$dog1 = new Dog("Barker");
$dog2 = new Dog("Amigo");
echo $dog1->bark();
echo $dog2->greet();
?>

 

3.內建function

is_a:確認object是否屬於此class

 

property_exists:確認property是否存在

 

method_exists:確認method是否存在

 

EX:

<p>
<?php
class Person {
public $isAlive = true;

function __construct($name) {
$this->name = $name;
}

public function dance() {
return "I'm dancing!";
}
}

$me = new Person("Shane");
if (is_a($me, "Person")) {
echo "I'm a person, ";
}
if (property_exists($me, "name")) {
echo "I have a name, ";
}
if (method_exists($me, "dance")) {
echo "and I know how to dance!";
}
?>

 

 4.extends

接續class之property至其他class中

 

<?php
class Shape {
public $hasSides = true;
}

class Square extends Shape{ //將Shape中的Property延伸給Square使用

}

$square = new Square();

if (property_exists($square, "hasSides") ) {//確認Property"hasSides"是否在$square中
echo "I have sides!";
}
?>

 

5.final 不可改變之function

使用final可以確保某一個class內的method被其他extends的class複寫取代

 

EX:

class Vehicle {
  final public function drive() {
    return "I'm drivin' here!";
  }
}

 

如上所示,當method"drive"使用final後,如果其他class內再使用此method取代,則會發生error

 

6.const 不可改變之變數

 

使用const可以將變數的值設為不可以複寫取代

 

EX:

class Immortal extends Person {
  // Immortals never die!
  const alive = true;
}

// If true...
if (Immortal::alive) {
  echo "I live forever!";
}
// echoes "I live forever!"

注意!const後的變數不需要加上$

 

"::"為使用const之變數在某個class內之必須 就像"->"一樣

 

7.static

使用static可以讓property 及method不須使用"new"創建一個新的變數(也就是$objname = new className{})

EX:

class Person {
  public static $isAlive = "Yep!"
  public static function greet() {
    echo "Hello there!";
  }
}

echo Person::$isAlive;
// prints "Yep!"
Person::greet();
// prints "Hello there!"

 

 

 

 

arrow
arrow
    全站熱搜

    Joseph Lin 發表在 痞客邦 留言(0) 人氣()