菜鳥的php (part2)

菜鳥的php (part2)

最近碰到了一點php, 分享一下學習筆記, 不過不管是工作還是學習重心都還是放在前端, 所以內容真的都寫的很粗淺, 只是個出於興趣的學習筆記而已

Object

Obj->method/prop

取用物件中屬性或方法的方法, 是使用箭頭來連接物件與該屬性/方法名

結合html - 取得表單submit後傳來的值

html
使用name屬性來跟php溝通, submit後表單中的欄位會post(method)到register.php(action)

1
2
3
4
5
6
7
8
9
10
11
12
<form id="loginForm" action="register.php" method="POST">
<h2>Login to your account</h2>
<p>
<label for="loginUsername">username</label>
<input id="loginUsername" name="loginUsername" type="text" required>
</p>
<p>
<label for="loginPassword">Password</label>
<input id="loginPassword" name="loginPassword" type="password" required>
</p>
<button type="submit" name="loginButton">Log in</button>
</form>

php - 若按下loginButton, post資料, php端取得value

1
2
3
4
5
6
if(isset($_POST['registerButton'])) {
//register button was pressed
//variable // 取得POST回傳資料中的registerUsername (match name in html)
//php變數 // html中name = registerUsername
$username = $_POST['registerUsername'];
}

$_POST['html-name-property']

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  class Account {
// private variable only exists in thie instance of this class
private $privateVariables;

// constructor two _ _
// invoked first when a class is created
public function __construct() {
// do something...
}

public function fn($param) {
// this, the instance of this class
$this->privateFn($param);
}
// public vs private - private fns can only be called within this class
private function privateFn($param) {
// do something or return...
return;
}
}
}

注意點:

  1. 在php, this的指向跟js一樣嗎?
    目前看起來, 類別中的this是指向目前產生中的物件實例
  2. private和public的差異?
    private只能被該類別的實例呼叫, 不能被外部變數使用(類似js中的物件方法? 繼承屬性?)

static

若是想要存放一些固定不變的常數, 可以使用一個class來封裝, 並以static的方式使用

1
2
3
4
5
6
// store all the error msgs
class Constants {
//with static, we don't need to create any instance of this class before using this variables
// usage: outside of this class, Constants::$aStaticValue
public static $aStaticValue = "i am static!!!!";
}

在呼叫上跟一般的變數不同
Classname::$staticValue

注意!使用時我們不需要先產生該class的實例, 而是可以直接呼叫

include

若是想將複雜的檔案拆分成一個個模組, 就需要使用include來載入模組

1
2
3
4
// import external file
// use RELATIVE PATH
// be careful with the dependency!
include('includes/class/Account.php');

要注意模組之間相依性的問題喔!

頁面跳轉

1
header("Location: index.php");
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×