PHP 初階課程 Part. 3 - Functions and brief intro to Object-Oriented PHP
-
Upload
li-wei-lu -
Category
Engineering
-
view
88 -
download
2
Transcript of PHP 初階課程 Part. 3 - Functions and brief intro to Object-Oriented PHP
PHP 初階 - 課程三 Benson Lu
2014
Overview
function
Object-Oriented Programming
Built-in Function
strlen() substr() strtoupper() strtolower() strpos()
String 相關
length of string substring string to upper case string to lower case position of string
Built-in Function
array() array_push() count() sort() array_merge() join()
Array 相關
declare array push an element into array count the elements in array sort the elements merge two array output and separate into string
Built-in Function
round() rand()
Math 相關
Round the number into integer Random a number by given min and max
Built-in Function
print_r() var_dump() die; exit();
Debug 相關
print on screen dump the type and its content Die exit
Exercise
1. 創⼀一個 array,push 三個名字進去 2. 將名稱排序印出來 3. Random 選出 Winner 4. 把 Winner 的名字⽤用英⽂文⼤大寫印出來
Note有的要丟參數,有的不⽤用。
Note
有的有回傳值,有的沒有。
有的要丟參數,有的不⽤用。
Note
有的有回傳值,有的沒有。
有的要丟參數,有的不⽤用。
這中間,⼀一去⼀一回,⼀一定有東⻄西被完成了!
MAGIC!
Syntaxfunction name() { // Your code goes here }
function 宣告後,即代表我們可以使⽤用。 但如果要讓 function 被執⾏行。
需要 call function
Local Scopefunction name() { $myAge = 20;
echo $myData; } // Error echo $myData;
function 裡宣告的變數,屬於 local scope。 意思是當 function 執⾏行結束,變數也會跟著被釋放。
Exercise
1. helloWorld() 2. greetings() one params, two params 3. 加 減 乘 除
Object-Orientedobject
現實世界中的每個東⻄西,每⼀一個存在 都是⼀一種物件
物件
可以⽤用各種 屬性 以及 功能 來表達
⼈人 屬性:名字, ⾝身⾼高, 體重功能:⾛走路,說話,思考
狗 屬性:名字, 顏⾊色, 體重功能:跑,叫
Object-Orientedclass類別
類別就是,我們在程式中⽤用來 表⽰示物件 的⽅方式
其中包含 properties 以及 methods
Class
<?php
class dog { public $name;
public function bark() { echo “woof”; } }
?>
propertymethod
class name
Class
Icon Created by Dimitry Sunseifer from the Noun Project
class 只是⼀一個物件的藍圖、描述。
我們必須使⽤用這個物件,把物件 new 出來。
Classusage
<?php require(‘dog.php’);
$pet = new dog(); $pet->name = ‘wanwan’;
echo “My pet {$pet->name} says: ”; $pet->bark();
?>
new 使⽤用⽅方式
Classusage
<?php require(‘dog.php’);
$pet = new dog(); $pet->name = ‘wanwan’;
echo “My pet {$pet->name} says: ”; $pet->bark();
?>
new 使⽤用⽅方式
Classusage
$thisclass 內呼叫變數或⽅方法
<?php class dog { public $name; public function bark() {
echo $this->name .“ says ‘woof’”; } } ?>
Constructor__constructor()
new 出物件時,會⽴立即被執⾏行的⽅方法
<?php class dog { public $name; public __constructor($name) { $this->name = $name; } public function bark() { echo $this->name .“ says ‘woof’”; } } ?>
Exercise1. 寫⼀一個 profiles 的物件 2. 包含⼀一個 array 存⼈人名 (string) 3. 寫⼀一個 __constructor 可以傳⼊入預設 array 4. 寫⼀一個 method 可以新增 profile 5. 寫⼀一個 method 印出所有 profile, ⽤用以下格式
Current Profile ——————— 1. Benson 2. Sally 3. QQ
6. 寫⼀一個 method 印出 profile 總數
Thank You