Javascript : Object 1

9:07 PTG 0 Comments A+ a-

Objek membenarkan kita menyimpan properties dan beberapa nilai bagi object itu sendiri. Bagaimana kita nak membuat simple Object? Declare object perlu ada: 1) var 2) diikuti dengan nama objek 3) diikuti dengan tanda sama = 4) Setiap objek kemudian mempunyai tanda { 5) ada info didalam breket { tadi 6) berakhir dengan } Ini adalah contoh dimana info tiada didalam breket.

var bob = {};


Ini pula contoh objek terdiri daripada info yang dikenali sebagai property. Kaedah memasukkan property adalah nama property, diikuti tanda noktah bertindih( : ) dan nilai bagi property tersebut. Jika kita mempunyai banyak property, ianya perlu dipisahkan dengan tanda koma ( , ). Contoh seperti dibawah:



var Spencer = {
age: 22,
country: "United States"
};

// make your own object here called me
var me = {
age:27,
country:"Pulai Chondong"
};


Akses Properties Dalam Object Cara Pertama

Guna Object Literal Notation - Dot Notation

Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam braket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation {} .

1) Dot Notation

Cara mudah adalah Var = .



var bob = {
name: "Bob Smith",
age: 30
};
var susan = {
name: "Susan Jordan",
age: 25
};
// here we save Bob's information
var name1 = bob.name;
var age1 = bob.age;
// finish this code by saving Susan's information
var name2 =susan.name;
var age2 = susan.age;


Akses Properties Dalam Object Cara Kedua

Guna Object literal notation - Bracket Notation


Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam curly bracket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation [] .

1) Bracket Notation

// Take a look at our next example object, a dog
var dog = {
species: "greyhound",
weight: 60,
age: 4
};

var species = dog["species"];
// fill in the code to save the weight and age using bracket notation
var weight = dog["weight"];
var age =dog["age"];


Akses Properties Dalam Object Cara Ketiga
Constructor

Apa itu constructor? Constructor adalah cara mencipta objek tanpa curly bracket {}. Cipta objek menggunakan constructor iaitu mencipta objek kosong terlebih dahulu () dan syntaxnya adalah :


var objectName = new Object();


Kita sudah istihar objek tanpa properties.



var bob = new Object();



Bagaimana pula ingin masukkan properties? dengan cara kita create nama property tersebut contoh nama @ umur selepas . dan kemudian assign kepada nilai yang dikehendaki. Lihat contoh:


var bob = new Object();
bob.nama = "Bob Amirul";
bob.umur = 30;

Javascript: For (var property in dog)

5:14 PG 0 Comments A+ a-


var dog = {
species: "bulldog",
age: 3,
color: brown
};

for(var property in dog) {
console.log(property);
}


The words var and in are keywords. We need them to always be there. We can replace dog with any object that we want the for-in loop to run through. And you can think of property as a placeholder variable. You can use any word you want here.

In English, what is the code doing? It says: Assign the first property of the dog object to the variable property. Run the code (here, it is to print property to console). Then assign the second property of the dog object to the variable property. Again, run the code in the curly brackets. Keep repeating this until all the properties of the dog have been assigned to property.

Javascript: Object

2:34 PG 0 Comments A+ a-

 

- - - B a s i c s - - -

Each Object has one or more properties.
Each property consists of a property-key and it's associated value.

 var object1 = {
name: "First"
}


So object1 has 1 property
a name property with property-key name and it's associated string VALUE "FIRST"

OR

var myObj = {
type: 'fancy',
disposition: 'sunny'
}


myObj has 2 properties seperated by a comma-,,
a type property with property-key type and an associated string VALUE 'fancy'
a disposition-property with property-key disposition and
..an associated string VALUE 'sunny'.

= = = = = = = = = = = = = = = = = = = = = = =
To create an Object,
you can use the literal notation,
you directly create an Instance of the object, with the
properties being separated by a comma-,


var myObj = {
type: 'fancy',
disposition: 'sunny'
};


OR
You create an Object by the construct notation.
First you create an empty Object by way of either
myObj = new Object(); or myObj = {};
and then you attach its properties using the syntax
object-name.property-key = it's-associated-value ;
( this.name = x ; )

thus:

var myObj = {};
myObj.type = 'fancy';
myObj.disposition = 'sunny';



OR

There is also the facility Class construct notation.
The name should then start with a Capital-letter



var Person = function( theName, theAge ) {
this.name = theName;
this.age = theAge;
this.displayInstance = function() {
console.log("The displayInstance -output-"+
"\n============================" +
"\n\t name: " + this.name +
"\n\t age: " + this.age);
};
};
//now create an Instance of this Class-object
var myObj = new Person("Classy_Rocker",20);
//call the Method displayInstance which takes NO parameters
myObj.displayInstance();
console.log( myObj );


As you can see i created a function within this constructor,
they now call this function a Method.
So if in near future the course is asking you to create a method you now know
that you have to create
a property-key with an associated value being a function within an Object.

The Eight Levels of Programmers | 8 Tahap Skill Programmer

1:29 PG 0 Comments A+ a-

You want to rock, naturally! Or at least be a rockstar programmer. It's not a question that typically gets a serious answer – sort of like that other old groan-inducing interview chestnut, "what's your greatest weakness?" It's that you sometimes rock too hard, right? Innocent bystanders could get hurt.

But I think this is a different and more serious class of question, one that deserves real consideration. Not for the interviewer's benefit, but for your own benefit.

The "where do you see yourself in five years" question is sort of glib, and most people have a pat answer they give to interviewers. But it does raise some deeper concerns: what is the potential career path for a software developer? Sure, we do this stuff because we love it, and we're very fortunate in that regard. But will you be sitting in front of your computer programming when you're 50? When you're 60? What is the best possible career outcome for a programmer who aspires to be.. well, a programmer?

What if I told you, with tongue firmly planted in cheek, that there were Eight Levels of Programmers?

  1. Dead Programmer

    This is the highest level. Your code has survived and transcended your death. You are a part of the permanent historical record of computing. Other programmers study your work and writing. You may have won a Turing Award, or written influential papers, or invented one or more pieces of fundamental technology that have affected the course of programming as we know it. You don't just have a wikipedia entry – there are entire websites dedicated to studying your life and work.

    Very few programmers ever achieve this level in their own lifetimes.

    Examples: Dijkstra, Knuth, Kay

  2. Successful Programmer

    Programmers who are both well known and have created entire businesses – perhaps even whole industries – around their code. These programmers have given themselves the real freedom zero: the freedom to decide for themselves what they want to work on. And to share that freedom with their fellow programmers.

    This is the level to which most programmers should aspire. Getting to this level often depends more on business skills than programming.

    Examples: Gates, Carmack, DHH

  3. Famous Programmer

    This is also a good place to be, but not unless you also have a day job.

    You're famous in programming circles. But being famous doesn't necessarily mean you can turn a profit and support yourself. Famous is good, but successful is better. You probably work for a large, well known technology company, an influential small company, or you're a part of a modest startup team. Either way, other programmers have heard of you, and you're having a positive impact on the field.

  4. Working Programmer

    You have a successful career as a software developer. Your skills are always in demand and you never have to look very long or hard to find a great job. Your peers respect you. Every company you work with is improved and enriched in some way by your presence.

    But where do you go from there?

  5. Average Programmer

    At this level you are a good enough programmer to realize that you're not a great programmer. And you might never be.

    Talent often has little do do with success. You can be very successful if you have business and people skills. If you are an average programmer but manage to make a living at it then you aretalented, just not necessarily at coding.

    Don't knock the value of self-awareness. It's more rare than you realize. There's nothing wrong with lacking talent. Be bold. Figure out what you're good at, and pursue it. Aggressively.

  6. Amateur Programmer

    An amateur programmer loves to code, and it shows: they might be a promising student or intern, or perhaps they're contributing to open source projects, or building interesting "just for fun" applications or websites in their spare time. Their code and ideas show promise and enthusiasm.

    Being an amateur is a good thing; from this level one can rapidly rise to become a working programmer.

  7. Unknown Programmer

    The proverbial typical programmer. Joe Coder. Competent (usually) but unremarkable. Probably works for a large, anonymous MegaCorp. It's just a job, not their entire life. Nothing wrong with that, either.

  8. Bad Programmer

    People who somehow fell into the programmer role without an iota of skill or ability. Everything they touch turns into pain and suffering for their fellow programmers – with the possible exception of other Bad Programmers, who lack even the rudimentary skill required to tell that they're working with another Bad Programmer.

    Which is, perhaps, the hallmark of all Bad Programmers. These people have no business writing code of any kind – but they do, anyway.

These levels aren't entirely serious. Not every programmer aspires to the same things in their career. But it's illuminating to consider what a programmer could accomplish in ten years, twenty years, or thirty years – perhaps even a lifetime. Which notable programmers do you admire the most? What did they accomplish to earn your admiration?

In short, what do you wanna do with your life?

Source: http://www.devbattles.com/en/sand/post-765-The+Eight+Levels+of+Programmers

Javascript: Loop Mastery Practice

7:28 PTG 0 Comments A+ a-

 

LatihanKetiga2Loop

LATIHAN

Laksanakan ketiga-tiga For, Do/While dan While dalam satu aturcara.

// Write your code below!

var testFor= function(){
for (i=1;i<10;i++){
console.log ("ini adalah loop bagi for" +i);
};
};


var testDoWhile= function(){
hidupkanLoopDo=true;
do {
console.log ("Ini adalah loop bagi do untuk kali ini sahaja");
}while (hidupkanLoopDo=false);

};

var testWhile=function(){
i=1;
while(i<10){
console.log ("Ini adalah loop bagi While yang ke"+i);
++i;
}
}

testFor();
testDoWhile();
testWhile();







ini adalah loop bagi for1
ini adalah loop bagi for2
ini adalah loop bagi for3
ini adalah loop bagi for4
ini adalah loop bagi for5
ini adalah loop bagi for6
ini adalah loop bagi for7
ini adalah loop bagi for8
ini adalah loop bagi for9
Ini adalah loop bagi do untuk kali ini sahaja
Ini adalah loop bagi While yang ke1
Ini adalah loop bagi While yang ke2
Ini adalah loop bagi While yang ke3
Ini adalah loop bagi While yang ke4
Ini adalah loop bagi While yang ke5
Ini adalah loop bagi While yang ke6
Ini adalah loop bagi While yang ke7
Ini adalah loop bagi While yang ke8
Ini adalah loop bagi While yang ke9

Javascript : Do / While

7:12 PTG 0 Comments A+ a-

 

Kadang-kadang, kita ingin loop kita berjalan at least satu kali. Oleh itu kita akan menggunakan Do/While untuk jalan mudah.

var loopCondition = false;

do {
console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
} while (loopCondition);


It runs once because do tells it to, but then never again because loopCondition is false!



LATIHAN



1) Guna Do/While.

2) Minta input dari user


3) Display di console.log


4) Matikan dengan falsekan kenyataan.



var getToDaChoppa = function(){
// Write your do/while loop here!
do {
var x = prompt ("Apa pilihan anda?");
console.log (x);
} while (jalankan=false);

};

getToDaChoppa();

Javascript : While Part 1

7:41 PG 0 Comments A+ a-

 

Jika for digunakan ketika kita tahu bila ia berhenti, While pula digunakan ketika kita tidak tahu bilakah dia akan berhenti.

 

understand = true;

while(understand === true){
console.log("I'm learning while loops!");
//Change the value of 'understand' here!
understand=false;

}


Namun pastikan didalam while tersebut, ada jalan untuk dia berhenti dan keluar dari while tersebut dan tidaklah ianya berpusing sahaja forever dan akhirnya membawa kepada crash sesuatu sistem akibat while yang tidak keluar2 atau infinity.


contoh diatas adalah understand=false;  adalah satu cara untuk kita hentikan penyataan while.


Brevity is the soul of programming


Ketahuilah brevity adalah key penting dlm programming, oleh itu, code diatas kita boleh ringkaskan menjadi:

understand = true;

while(understand){
console.log("I'm learning while loops!");
//Change the value of 'understand' here!
understand=false;

}

understand itu kita tidak perlu tanya ===true didalam while.


Penyataan diringkaskan seperti dibawah:

var bool = true;
while(bool){
//Do something
}


daripada:

var bool = true;
while(bool === true){
//Do something
}

 


Kedua-dua adalah sama sahaja, melainkan brevity dan kecepatan meringkas sahaja. Elakkan written the less succinct version dalam programming kita, sebaliknya teruskan  Correct it to the more elegant version!

var bool = true;

while(bool){
console.log("Less in coding is too cool!");
bool = false;
}
LATIHAN
Bina satu coding menggunakan while, dengan penyataaan I'm looping! sebanyak tiga kali menggunakan while.
Bagaimana menggunakan counter untuk while? Set variable kepada 0 di luar While, dan set counter tersebut bertambah semasa looping, dan set penyataan berhenti di While dengan nyatakan bilangan ke berapa ianya patut berhenti atau berapa kali ianya TRUE.
//Remember to set your condition outside the loop!


var loop = function(){
while(count <3){
//Your code goes here!
console.log("I'm looping!");
count++;
}
};

var count=0;
loop();





I'm looping!
I'm looping!
I'm looping!

 


CONTOH

//Remember to make your condition true outside the loop!

var soloLoop = function(){
//Your code goes here!

loopSekali=true;

while (loopSekali){
console.log("Looped once!");
loopSekali = false;
}

};

soloLoop();





Looped once!

Javascript : Loop Part 2 & Push()

6:19 PG 0 Comments A+ a-


Perbezaan Array antara dua patah perkataan @ lebih dengan satu patah perkataan. Tengok cara dia ambik aksara bagi [0].

Untuk dua perkataan atau lebih, Array akan tarik perkataan.

var myArray = ['hello', 'world'];
myArray[0]; // equals 'hello'


 



Manakala untuk satu patah perkataan, Array akan tarik aksara



var myName = 'Eric';
myName[0]; // equals 'E'


JavaScript Array push() Method



Digunakan untuk menambah new item kedalam array. Ianya berada di hujung sekali data array.



var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");






Banana,Orange,Apple,Mango,Kiwi

Javascript : Loop Part 2- Array

1:17 PG 0 Comments A+ a-

 

Variable boleh simpan number dan string, namun kita hanya boleh store 1 number atau satu string sahaja.
Mujurlah kita punyai array. Apa guna array?

a. store lists of data
b. can store different data types at the same time
c. are ordered so the position of each piece of data is fixed

var arrayName = [data, data, data];

var names = ["Mao","Gandhi","Mandela"];

var sizes = [4, 6, 3, 2, 1, 9];

var mixed = [34, "candy", "blue", 11];


 



Bila mana anda lihat  data dilingkungi dgn tanda [ ], it is an array.



Contoh:



var profile = ["Nik","IT Manager",32,4];
console.log(profile);






["Nik","IT Manager",32,4];



  1. First element in the array: profile[0]


  2. Third element in the array: profile[2]



atau jika ingin mendapatkan data 32, maka gunakan profile[2]



console.log(profile[2]);



Kalau ada 4 elemen dalam array, ok la. Bagaimana dengan 100 elemen dalam Array? Kita akan gunakan Array.



// Let's print out every element of an array using a for loop

var cities = [ "Pulai Chondong", "Melbourne", "Amman", "Helsinki", "NYC", "Kota Bharu"];

for (var i = 0; i < cities.length; i++) {
console.log("I would like to visit " + cities[i]);
}








I would like to visit Melbourne
I would like to visit Amman
I would like to visit Helsinki
I would like to visit NYC



Keyword, ianya berhenti sebelum cities.length

Javascript: Loop part 1

11:39 PTG 0 Comments A+ a-

 

Gunakan loop untuk mempermudahkan urusan kita.

// Write five console.log statements.

console.log(1);
console.log(2;
console.log(3);
console.log(4);
console.log(5);

Kepada:


for (var counter = 1; counter < 6; counter++) {
console.log(counter);
}

atau


for (var i = 1; i < 6; i = i + 1){
console.log(i);
}


 



contoh bermula dari 4 hingga ke 23:



for (var i = 4; i < 24; i = i + 1) {
console.log(i);
}


 



We can increment up by any value by writing i += x, where x is how much we want to increment up by.e.g., i += 3 counts up by 3s.





We can decrement down by any value by writing i -= x.



Contoh:




-Make it start counting from 5. Please!


-Stop the counting when it prints out 50.


-Only count every fifth number. So we want to increment i by 5.



for (var i = 5; i < 51; i+=5) {
console.log(i);
}


Contoh loop menurun adalah: 10 hingga ke 0.


for (var i = 10; i >= 0; i--) {
console.log(i);
}


 


Once more, for practice: write a forloop that gets the computer to count down from 100 until 0 by 5. This time, make sure not to print 0.

// Write your very own for loop!

for (var i=100;i>0;i-=5)
{
console.log(i);
}

Java Script: Bina Permainan Rock, Paper, Scissors

10:25 PTG 1 Comments A+ a-

 

Latihan membina game mudah.


- Declare a variable called userChoice.
- Make the variable equal to the answer we get by asking the user "Do you choose rock, paper or scissors?"

var userChoice = prompt("Do you choose rock, paper or scissors?");


 



- Under your previous code, declare a variable called computerChoice and make it equal to Math.random().



- Print out computerChoice so you can see how Math.random() works. This step isn't needed for the game - just useful for learning!



var userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice=Math.random();
console.log (computerChoice);


We have computerChoice but it now equals a random number between 0 and 1. We need to somehow translate this random number into a random choice of rock, paper, or scissors. How do we do this?!



-If computerChoice is between 0 and 0.33, make computerChoice equal to "rock".



-If computerChoice is between 0.34 and 0.66, make computerChoice equal to "paper".



-If computerChoice is between 0.67 and 1, make computerChoice equal to "scissors".



 



var userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice=Math.random();
console.log (computerChoice);
if ((computerChoice >= 0) && (computerChoice <=0.33))
{
console.log (computerChoice);
console.log ("rock");
}
else if ((computerChoice >= 0.34) && (computerChoice <=0.66))
{
console.log (computerChoice);
console.log ("paper");
}
else
{
console.log (computerChoice);
console.log ("scissors");
}


 



-We carried over the code from the previous section, but it is a comment. Leave it there for now.



-Below the comment, declare a function called compare.

It takes two parameters, choice1 and choice2.



-Inside the function, write an if statement. If choice1 === choice2, then return "The result is a tie!"



var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1,choice2){
if (choice1===choice2) {
return "The result is a tie!";
}
};

compare(computerChoice,userChoice);


 








Computer: rock
"The result is a tie!"



 



 



What if choice1 is "rock"? Given choice1 is "rock",



a. if choice2 === "scissors", then "rock" wins.

b. if choice2 === "paper", then "paper" wins.





How do we structure this? It's a bit different from what we have already seen. We will first have an if statement. And then the code inside that if statement will be... another if statement!



 



var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1,choice2){
if (choice1===choice2) {
return "The result is a tie!";
}
else if (choice1=="rock")
{
if (choice2 ==="scissors")
return "rock wins";
else
{
return "paper wins"
}
}
};

compare(computerChoice,userChoice);


 



SIAP!

Javascript 5 : Function Part 3 ( Dengan 2 Parameter)

1:10 PG 0 Comments A+ a-

 

Function juga dapat dijalankan dengan lebih dari 1 parameter. Lihat contoh dibawah

// Write your function starting on line 3
var areaBox= function(length,width) {
return length * width
};

areaBox(6,2);

Function untuk perimeter of a rectangle memerlukan dua parameter dan formulanya adalah : length + length + width + width. Contoh untuk function pengiraan rectangle parameter adalah seperti:

var perimeterBox= function(length,width) {
return length + length + width + width
};

perimeterBox(6,2);
 
SCOPE

Scope mungkin global atau local. Variable yang di definasikan di luar function, boleh diakses dimana-mana once diorang di declare. Mereka dipanggil  global variables and their scope is global.

For example

var globalVar = "hello";

var foo = function() {
console.log(globalVar); // prints "hello"
}




hello

Variable globalVar boleh diakses di mana-mana termasuk didalam function foo.


Manakala variable yang dideclare didalam function dikenali sebagai local variables. Mereka tidak boleh diakses di luar dari function tersebut.


For example

var bar = function() {
var localVar = "howdy";
}

console.log(localVar); // error




// error

Error terjadi kerana kita cuba print localVar di luar function.


Dibawah adalah perbezaan yang jelas penggunaan scope global dan local.

var my_number = 7; //this has global scope

var timesTwo = function(number) {
my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);


 





Inside the function my_number is: 
14
Outside the function my_number is:
14
CONTOH LOCAL (tambar perkataan var didalam function)
var my_number = 7; //this has global scope

var timesTwo = function(number) {
var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);




Inside the function my_number is: 
14
Outside the function my_number is:
7

Javascript 5 : Function Part 2

8:45 PTG 0 Comments A+ a-

 

Sekarang kita sudah boleh memanggil FUNCTION. Namun ianya bukan sekadar untuk print dan display sahaja. FUNCTION juga berguna untuk memproses dan return kembali nilai tersebut.

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
return number * 2;
};

// Call timesTwo here!
var newNumber =timesTwo(2);
console.log(newNumber);



timesTwo adalah function yang digunakan untuk memproses nilai yang dihantar dengan mendarabkan dengan 2. Function yang dipanggil yang disertakan dgn nilai yang dihantar, akan diproses didalam timesTwo dan dihantar kembali kepada pemanggil untuk tindakan seterusnya.



Contoh:



var quarter= function (number){
return number/4;
};



if (quarter(48) % 3 === 0 ) {
console.log("The statement is true");
} else {
console.log("The statement is false");
}







The statement is true

Javascript 5 : Function (Part 1–Intro)

6:30 PTG 0 Comments A+ a-

 

Memahami konsep IF/ELSE statement perlu dalam sesuatu penggunaan pengaturcaraan. Contoh IF/ELSE adalah seperti:

var speed = 65;

// Complete the condition in the ()s on line 4
if (speed > 80 )
{
// Use console.log() to print "Slow down"
console.log("Slow Down");
}
else
{
// Use console.log() to print "Drive safe"
console.log("Drive Safe");
}


Apa itu function? Fahami konsep function sebelum membuat programming. Function boleh diumpamakan  seperti membuat cake. Dengan andaian jalan dan cara membuat cake adalah sama, cuma mungkin input kemanisan atau bahan sahaja berbeza.



Function:



1) Panaskan api sehingga 300 darjah



2) Campur semua bahan ramuan kedalam mangkuk



3) Letakkan ramuan yang telah dicampur itu kedalam oven sehingga 30 minit.




Caranya sama, cuma output sahaja yang berbeza kerana input (jumlah ramuan, kandungan gula) mungkin berbeza.  Contoh 10 sudu gula+ramuan buat kek coklet(input), kemudian kita panggil function iaitu tiga step diatas. Input diproses dan mengeluarkan output berbeza bergantung kepada input yang diberikan.



 




// This is what a function looks like:

var divideByThree = function (number) {
var val = number / 3;
console.log(val);
};

// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!

divideByThree(6);


 



Kita menghantar nombor 6 untuk dimasukkan kedalam oven DivideByThree, Oven memproses dengan membahagikan 3 dengan 3, dan oven function mengeluarkan output iaitu 2. Jika kita masukkan input 9, function akan proses dgn bahagikan kepada 3 dan mengeluarkan output iaitu 3.




// Below is the greeting function!
// See line 7
// We can join strings together using the plus sign (+)
// See the hint for more details about how this works.

var greeting = function (name) {
console.log("Great to see you," + " " + name);
};

greeting("Mr Encraptor");
// On line 11, call the greeting function!







Great to see you, Mr Encraptor



 



Latihan:



1) Bina satu function, berikan nama FoodDemand



2) Kamu boleh masukkan apa sahaja nama makanan, tapi kami hanya ingin panggil dengan panggilan food sahaja untuk display apa yang kamu masukkan.



3) Akhiri dengan output seperti dibawah untuk display:

console.log("I want to eat" + " " + food);



 



// Write your foodDemand function below.
// Last hint: In your reusable block of code, end each line
// with a semicolon (;)
var foodDemand = function (food) {

console.log("I want to eat" + " " + food);

}

foodDemand("kek");







I want to eat kek



// Nicely written function:
var calculate = function (number) {
var val = number * 10;
console.log(val);
};


Contoh function sebelum dipanggil.

Cara panggil adalah tulis nama function dan letak input nombor yang dikehendaki.



contoh:



calculate(6);

Javascript 4: Variable

12:50 PG 0 Comments A+ a-

Variable atau pemboleh ubah adalah satu value yang kita declare value tersebut untuk memberi nilai pada pemboleh ubah tersebut.
var myAge=27;

console.log(myAge);



// PAPARAN: 27


Kita declare myAge dengan memberi arahan var myAge, kemudian kita masukkan nilai dengan arahan =27; Untuk coding yang complex, kita perlu menyimpan value siap-siap kedalam variable dengan specific dan case sensitive nama yang senang diingati, dan kita akan panggil variable ini di masa yang mana perlu padanya.





Kita telah melihat bagaimana mencipta variable. Sekarnag bagaimana untuk menggunakannya? Ianya berguna ketika anda memasukkan sesuatu nilai kedalam variable dan variable tersebut digunakan untuk formula atau pengiraan berasaskan variable yang telah dimasukkan. For example:

var myName = "Encraption Team";

myName.substring(0,5)



Jika dilihat disini, myName sekarang adalah diwakili oleh value 'Encraption Team'.

myName.substring(0,5)



pada zahirnya kelihatan ianya myName, tetapi ianya sebenarnya memegang value seperti dibawah

"Encraption Team".substring(0,5) 



iaitu nilainya adalah Encraption Team. Contoh penggunaan Variable adalah memberi value pada variable myCountry sebagai value Malaysia dan melakukan operasi keatas variable tersebut

// Declare a variable on line 3 called
// myCountry and give it a string value.
var myCountry = "Malaysia";


// Use console.log to print out the length of the variable myCountry.
console.log( myCountry.length);

// Use console.log to print out the first three letters of myCountry.
console.log(myCountry.substring(0,3) );


Paparan: 8


Mal


// On line 2, declare a variable myName and give it your name.
var myName = "Mr Encraptor";
// On line 4, use console.log to print out the myName variable.
console.log (myName);
// On line 7, change the value of myName to be just the first 2 
// letters of your name.
var myName = "Mr";
// On line 9, use console.log to print out the myName variable.
console.log (myName);


Paparan:


Mr Encraptor


Mr


On line 1, create a variable myColor and give it a string value.


On line 2, print the length of myColor to the console.


var myColor = "Green";
console.log(myColor.length);


Paparan:


5


// Not sure where to begin? Check the Hint!
var myNumber=27;
if
    (myNumber === 27)
    {
        console.log("I finished my first course!");
    }
    else
    {
         console.log("I cant finished my first course!");
    }


Paparan:


I finished my first course!


// Check if the user is ready to play!
confirm("I am ready to play!");
var age = prompt("What's your age");
if (age<=13)
{
    console.log ( "You cant play this game");
}
else
{
console.log ("please play it safely");
}


var_retrive_dari_prompt


Jika user masukkan melebihi 13, mereka boleh bermain game ini, sebaliknya mereka tidak dibenarkan bermain game ini.





// Check if the user is ready to play!
confirm("I am ready to play!");
var age = prompt("What's your age");
if (age<=13)
{
    console.log ( "You cant play this game");
}
else
{
console.log ("please play it safely");
}
console.log ("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");
console.log ("Suddenly, Bieber stops and says, 'Who wants to race me?'");
var userAnswer=prompt("Do you want to race Bieber on stage?");

if (userAnswer==="yes")
{
    console.log ( "You and Bieber start racing. It's neck and neck! You win by a shoelace!");
}
else
{
console.log ("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
}
var feedback=prompt("Please rate our game");
if (feedback>=8) 
{
    console.log("Thank you! We should race at the next concert!");
}
else
{
    console.log("I'll keep practicing coding and racing.");

}


Paparan:

Javascript 3: Substring

4:20 PTG 0 Comments A+ a-

Pernah melihat bagaimana tajuk email gmail dikerat contentnya di muka depan gmail kerana isinya panjang?

substring1

Jika diklik pada tajuk email tersebut, perkataan promotion(baris 1) dan product (baris ke-2) akan keluar namun ianya di kerat di muka hadapan Gmail. Ianya menggunakan kaedah substring.

Kiraan perkataan diulakan dengan 0.
0 1 2 3 4
| | | | |
h e l l o


"hello". substring(0, 2);

Paparan : HE // Be careful with the substring's letter positions!

"wonderful day".substring(3,7); 

Paparan: "derf"


0 - w


1 - o


2 - n


3 - d (bermula disini)


4 - e


5 - r


6 - f (berakhir disini iaitu sebelum no ke 7)


7 - u





Latihan:

a. "Jan" in "January"
b. "Melbourne is" in "Melbourne is great" (note the space!)
c. "burgers" in "Hamburgers"

Jawapan:

console.log("January".substring(0,3));
console.log("Melbourne is great".substring(0,12));
console.log("Hamburgers".substring(3,10));
  

Javascript 2: Nota Asas Javascript Part 2 - Condition IF ELSE

7:03 PTG 0 Comments A+ a-

Penggunaan If Condition Disertakan kerangka ringkas If Else. Setiap kali ingin membuat If Else, gunakan template ini dan isi condition semasa dan action yang hendak dilaksanakan.
if (condition) 
{
// if condition is true
// do this code
}
else // "otherwise"
{
// do this code instead
}

Contoh:


// Remember, the order and punctuation matter.
// If you get an error, check carefully, line by line.
// If you're really stuck, click "Stuck? Get a hint!"

if (5>6)
{ console.log ("The condition is true")
}
else //otherwise
{ console.log ("The condition is false")
}

Computer Tidak Bijak Sangat Komputer tidaklah bijak sangat, Syntax perlu diletakkan betul-betul pada tempatnya dan tidak boleh ditafsir sendiri oleh komputer. Jadi, kita perlu memperlajari cara meletak syntax dengan betul supaya komputer boleh faham apa yang kita ingin lakukan. Kita kena biasakan diri dengan susunan syntax sebelum bermadah pujangga. contoh dibawah ialah terdapat kesilapan meletak syntax ; dan menukar = kepada ===. Mengapa? = adalah untuk assign sesuatu variable manakala === adalah untuk comparison. Dengan adanya ; dan = maka computer ini terus pening dan akan keluar error tidak dapat run. SCRIPT SALAH

if (10 = 10); {
console.log("You got a true!");
} else {
console.log("You got a false!");
}

Kita kena buang terlebih dahulu semi-colon ; serta menggantikan = kepada === seperti dibawah

if (10 === 10) {
console.log("You got a true!");
} else {
console.log("You got a false!");
}

Contoh:

if  ("Jon".length * 2 / (2+1) ===2 )
{
console.log("The answer makes sense!");
}
else
{
console.log("Error Error Error");
}

Paparan: The answer makes sense! MODULO Modulo adalah reminder dalam pembahagian. Digunakan didalam programming selain untuk kira, juga untuk mengesan nombor ganjil dan genap.

// Below is an example of printing the remainder of 18/4 using modulo:
// console.log(18 % 4);
console.log(14 % 3);
console.log(99 % 8);
console.log(11 % 3);

Paparan: 2 3 2


//An example of an if/else statement with modulo in the condition


if  ("Jon".length * 2 / (2+1) ===2 )
if(10 % 5 ===0 )
{
console.log("The first number is even");
} else {
console.log("The first number is odd");
}

Paparan: The first number is even

Javascript 1: Nota Asas Javascript

5:39 PG 0 Comments A+ a-


"nixk".length


// PAPARAN: 4




4+3

// PAPARAN: 7



6/2


// PAPARAN: 3


// This is a comment that the computer will ignore.
// It is for your eyes only!
"cake".length
// Ini adalah komen dan komputer akan ignore baris ini.


// PAPARAN: 4


confirm('This is an example of using JS to create some interaction on a website. Click OK to continue!');


// PAPARAN: Dialog confirm



confirm ("I feel awesome!");
confirm ("I'm ready to go.");


// PAPARAN: Ada 2 Dialog confirm


prompt ("Where are you come from?");


// PAPARAN: Ada 1 dialog pertanyaan, bila dijawab Kelantan, result akan papar Kelantan


alert('Hello nixk, welcome to Code Avengers')

// PAPARAN: Keluar dialog alert


Data Types I & II: Numbers & Strings

Data mempunyai pelbagai jenis. Kita baru menggunakan dua iaitu number dan strings.

a. Number: Kuantiti dan boleh lakukan math.

b. Strings: adalah aksara a-z,space dan mungkin juga number, biasanya string digunakan sebagai label, nama dan isi didalam program kita

c. Jika ingin menjadikan number sebagai number dan bukan string, taip tanpa quotes ". Contoh: 190.12334.

d. JIka ingin menjadikan string, gunakan quotes ".



Data Type III: Booleans

Booleans digunakan untuk membandingkan dua perkara untuk mendapat keputusan samada true atau false.

23 > 10 is true
5 < 4 is false


"I'm coding like a champ".length >10

// PAPARAN: true


Console.log

console.log( 2*5)
console.log( "Hello")

// PAPARAN:
10
Hello

Penggunaan console log adalah untuk mengetahui apa sebenarnya computer sedang lakukan. Juga dikenali sebagai printing out.



// Here is an example of using the greater than (>) operator.
console.log(15 > 4); // 15 > 4 evaluates to true, so true is printed.

// Fill in with >, <, === so that the following print out true:
console.log("Xiao Hui".length < 122);
console.log("Goody Donaldson".length > 8);
console.log(8*2 == 16);

// PAPARAN:
true
true
true
true


if (10 >=7 ) {
console.log("You have a long name!" );
}

// PAPARAN:You have a long name!



if ("left".length >10 )
{
console.log("Let's go down the first road!");
}
else
{
// What should we do if the condition is false? Fill in here:
console.log("Let's go down the second road!");

}

// PAPARAN: Let's go down the second road!

Mobile Apps 3 : Gunakan Pages Sebagai Dailog

10:03 PTG 0 Comments A+ a-

 


<!--
* Mari Belajar PHP
* @copyright (c) 2015, Encraptor Inc. All Right Reserved
* @author Encraptor@gmail.com

* @link http://encraption.blogspot.com
* @version 20151
* @desc Mobile Apps 3 : Gunakan Pages Sebagai Dailog
* Fail: 3_PagesSebagaiDailog.php

-->

<!-- Tag <!DOCTYPE html> merupakan tag HTML5 -->
<!DOCTYPE html>
<html>
<head>

<!-- meta name untuk device mobile -->
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Kita perlu memanggil 3 perkara asas rujukan untuk mobile apps iaitu JQUERY, JQUERY MOBILE serta JQUERY MOBILE CSS-->

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>


<div data-role="page" id="pageone">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>

<div data-role="main" class="ui-content">
<p>Welcome!</p>
<a href="#pagetwo">Go to Dialog Page</a>
</div>

<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>

<!-- Untuk menjadikan sesuatu page itu menjadi dialog page, kita perlu set data-dialog="true" di page berkenaan -->

<div data-role="page" data-dialog="true" id="pagetwo">
<div data-role="header">
<h1>I'm A Dialog Box!</h1>
</div>

<div data-role="main" class="ui-content">
<p>The dialog box is different from a normal page, it is displayed on top of the current page and it will not span the entire width of the page. The dialog has also an icon of "X" in the header to close the box.</p>
<a href="#pageone">Go to Page One</a>
</div>

<div data-role="footer">
<h1>Footer Text In Dialog</h1>
</div>
</div>


</body>
</html>


 



3_PagesSebagaiDailog1



3_PagesSebagaiDailog2

Mobile Apps 2: Menambah Page Didalam Mobile Apps

9:53 PTG 0 Comments A+ a-

 


<!--
* Mari Belajar PHP
* @copyright (c) 2015, Encraptor Inc. All Right Reserved
* @author Encraptor@gmail.com

* @link http://encraption.blogspot.com
* @version 20151
* @desc Menambah Page Didalam Mobile Apps
* Fail: 2_tambahPageDanLink.php

-->

<!-- Tag <!DOCTYPE html> merupakan tag HTML5 -->


<!DOCTYPE html>
<html>
<head>
<!-- meta name untuk device mobile -->
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Kita perlu memanggil 3 perkara asas rujukan untuk mobile apps iaitu JQUERY, JQUERY MOBILE serta JQUERY MOBILE CSS-->

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>

<!-- Setiap page perlu diset <div data-role="page"> dan mempunyai tiga data-role iaitu header,main dan footer
Oleh kerana terdapat beberapa page, maka kita perlu letakkan id di page tersebut.
Setiap ID Page ada Nama Yang Unik. Contoh: id="pageone" dan id="pagetwo".
Cara panggil adalah href="#pagetwo" dan href="#pageone".
-->


<!-- Page pertama bernama pageone, nama tersebut di letakkan di ID sebelah data-role="page" -->
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>

<div data-role="main" class="ui-content">
<p>Welcome! If you click on the link below, it will take you to Page Two.</p>
<a href="#pagetwo">Go to Page Two</a>
</div>

<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>

<!-- Page pertama bernama pagetwo, nama tersebut di letakkan di ID sebelah data-role="page" -->
<div data-role="page" id="pagetwo">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>

<div data-role="main" class="ui-content">


<!-- Cara memanggil page tersebut dengan meletakkan # disebelah nama yang diberikan pada id page.
contoh: <a href="#pageone"> -->
<p>This is Page Two. If you click on the link below, it will take you to Page One.</p>
<a href="#pageone">Go to Page One</a>
</div>

<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>

</body>
</html>


2_tambahPageDanLink1



2_tambahPageDanLink2

Mobile Apps 1 : Asas-asas dalam Page

9:29 PTG 0 Comments A+ a-

<!--
* Mari Belajar PHP
* @copyright (c) 2015, Encraptor Inc. All Right Reserved
* @author Encraptor@gmail.com

* @link http://encraption.blogspot.com
* @version 20151
* @desc Penenrangan Asas bagi Mobile Apps didalam HTML5
* Fail: 1_AsasPageMobile.php

-->

<!-- Tag <!DOCTYPE html> merupakan tag HTML5 -->
<!DOCTYPE html>



<html>
<head>

<!-- meta name untuk device mobile -->

<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Kita perlu memanggil 3 perkara asas rujukan untuk mobile apps iaitu JQUERY, JQUERY MOBILE serta JQUERY MOBILE CSS-->

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>

<!-- Setiap page perlu diset <div data-role="page"> dan mempunyai tiga data-role iaitu header,main dan footer -->

<div data-role="page">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>

<div data-role="main" class="ui-content">
<p>I Am Now A Mobile Developer!!</p>
</div>

<div data-role="footer">
<h1>Footer Text</h1>
</div>
</div>

</body>
</html>


1_AsasPageMobile



 



Rujukan penting: W3Schools->JqueryMobile

Install Apache PHP MYSQL Dalam Linux elementary OS

8:34 PTG 0 Comments A+ a-

apt-get install mysql-server mysql-client

apt-get install apache2

apt-get install php5 libapache2-mod-php5

apt-cache search php5

apt-get install php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite p$

apt-get install phpmyadmin

/etc/init.d/apache2 restart

Mobile Apps–Memanggil Senarai Dari Database

9:36 PTG 0 Comments A+ a-

service 11.html (local)

<!DOCTYPE html>
<html>

<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>

<body>

<h1>Nama Sekolah</h1>
<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://ambo-kena.besaba.com/mreport/namasekolah.php";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";

for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Id +
"</td><td>" +
arr[i].Title +
"</td><td>" +
arr[i].Content +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>


 



 



namasekolah.php



<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("mysql.hostinger.my", "contoh_username_bro", "password_bro", "contoh_nama_database");

$result = $conn->query("SELECT post_id,post_title, post_content FROM posts");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Id":"' . $rs["post_id"] . '",';
$outp .= '"Title":"' . $rs["post_title"] . '",';
$outp .= '"Content":"'. $rs["post_content"] . '"}';
}
$outp .="]";

$conn->close();

echo($outp);
?>


 



Contoh printscreen:



mobile-apps-tarikdata



 



SQL:




-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 07, 2015 at 05:35 AM
-- Server version: 5.1.67
-- PHP Version: 5.2.17

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `u641767033_mrpt`
--

-- --------------------------------------------------------

--
-- Table structure for table `posts`
--

CREATE TABLE IF NOT EXISTS `posts` (
`post_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`post_title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`post_content` text COLLATE utf8_unicode_ci NOT NULL,
`post_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=90 ;

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`post_id`, `post_title`, `post_content`, `post_date`) VALUES
(1, 'MAAHAD MUHAMMADI (LELAKI)', '09-744 4003', '0000-00-00 00:00:00'),
(2, 'MAAHAD MUHAMMADI (PEREMPUAN)', '09-748 2549', '0000-00-00 00:00:00'),
(3, 'MAAHAD PENGAJIAN ISLAM', '09-748 3804', '0000-00-00 00:00:00');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

PHP Tutorials Examples Object Oriented Programming with PHP

10:13 PTG 0 Comments A+ a-

 

OOP was first invented for the purpose of physical modelling in the Simula-67.
Whilst there is no hard and fast definition of what Object Oriented Programming (OOP) is, we can define. So lets just use this loose definition for now and it is left to reader to make up their own minds about what a decent definition is. Object Oriented Programming (OOP) is a programming concept that treats functions and data as objects. OK, not the best definition but gives us an opening. The key word here is objects. As we progress through this tutorial we will see how data and functions can be represented as re-usable objects, thus cutting down on code and time.

What is an Object

Simply put, an oject is a bunch of variables and functions all lumped into a single entity. The object can then be called rather than calling the variables or functions themselves. Within an object there are methods and properties. The methods are functions that manipulate data withing the object. The properties are variables that hold information about the object.

What is a Class

A class is the blueprint for your object. The class contains the methods and properties, or the charactaristics of the object. It defines the object. Lets just start with some examples to see how it all pieces together. We will use a vehicle as our object. All vehicles share similar charactaristics, eg: number of doors, they are painted some color, they each have a price. All vehicles do similar things also, drive, turn left, turn right, stop etc. These can be described as functions, or in OOP parlance, methods. So, the class holds the definition, and the object holds the value. You declare class in PHP by using the class keyword.
<?php
class vehicle{
/*** define public properties ***/
/*** the color of the vehicle ***/
public $color;
/*** the number of doors ***/
public $num_doors;
/*** the price of the vehicle ***/
public $price;
/*** the shape of the vehicle ***/
public $shape;
/*** the brand of vehicle ***/
public $brand;
/*** the constructor ***/
public function __construct(){
  echo 'About this Vehicle.<br />';
}
/*** define some public methods ***/
/*** a method to show the vehicle price ***/
public function showPrice(){
  echo 'This vehicle costs '.$this->price.'.<br />';
}
/*** a method to show the number of doors ***/
public function numDoors(){
  echo 'This vehicle has '.$this->num_doors.' doors.<br />';
}
/*** method to drive the vehicle ***/
public function drive(){
  echo 'VRRROOOOOOM!!!';
}
} /*** end of class ***/
?>
With this simple class definition we can now create one, or many, vehicle objects. Lets see how its done, then we will step through it all. To create a new object from the class definition we use the new keyword.

<?php
/*** create a new vehicle object ***/
$vehicle = new vehicle;
/*** the brand of vehicle ***/
$vehicle->brand = 'Porsche';
/*** the shape of vehicle ***/
$vehicle->shape = 'Coupe';
/*** the color of the vehicle ***/
$vehicle->color = 'Red';
/*** number of doors ***/
$vehicle->num_doors = 2;
/*** cost of the vehicle ***/
$vehicle->price = 100000;
/*** call the showPrice method ***/
$vehicle->showPrice();
/*** call the numDoors method ***/
$vehicle->numDoors();
/*** drive the vehicle ***/
$vehicle->drive();
?>
Using the combination of the two code boxes above, you should have something like..
About this vehicle.
This vehicle costs 100000.
This vehicle has 2 doors.



Lets step through the class definition first to see what its all about.

We began the class with the class keyword. This tells PHP that what follows is a class definition.



<?php
class vehicle{
?>
Next we declared some variables, or as they are known in the OOP world, properties.



<?php
/*** the color of the vehicle ***/
public $color;
/*** the number of doors ***/
public $num_doors;
/*** the price of the vehicle ***/
public $price;
/*** the shape of the vehicle ***/
public $shape;
/*** the brand of vehicle ***/
public $brand;
?>

The properties are the individual charactaristics of the vehicle object. The public declares that this property may be accessed within the public scope. This means you may set it from within your code. Next in the class definition is this code..



<?php
/*** the constructor ***/
public function __construct(){
echo 'About this vehicle.<br />';
}
?>
The constructor method (function) is a special function that is executed every time a new object is created or "instantiated". If a class needs to do something before running some code, then this is the place to do it. It is often used to set properties within the class. You may pass a variable directly to the constructor from your code, but more of that later. Following the constructor is several methods (functions) that do things. These methods are also preceded by the public meaning they are available with the scope of your code.


<?php
/*** a method to show the vehicle price ***/
public function showPrice(){
echo 'This vehicle costs '.$this->price.'.<br />';
}
/*** a method to show the number of doors ***/
public function numDoors(){
echo 'This vehicle has '.$this->num_doors.' doors.<br />';
}
/*** method to drive the vehicle ***/
public function drive(){
echo 'VRRROOOOOOM';
}
?>


As you see above, our methods are similar to normal PHP functions. However you may note the use of variables like $this->price and $this->num_doors. The keyword $this is used to refer to properties or methods within the class itself. The $this keyword is reserved in PHP, so it cannot be used as a variable or property name. Finally we finished our class definition with a closing }. I like to put a comment beside it so I dont delete it or get it confused with a function I am writing.



Following on from the class definition we see our userland code. This is the code we use to instantiate (create) a new instance, or new object, of our vehicle class. As mentioned earlier we do this with the use of the new keyword.



<?php
/*** create a new vehicle object ***/
$vehicle = new vehicle;
?>


The code above creates a new object from our class definition called $vehicle. It is at this time that the constructor is called and any code within the constructor is executed. Once we have a new object we can then begin to assign values to the properties of that object as seen here.



<?php
/*** the brand of vehicle ***/
$vehicle->brand = 'Porsche';
/*** the shape of vehicle ***/
$vehicle->shape = 'Coupe';
/*** the color of the vehicle ***/
$vehicle->color = 'Red';
/*** number of doors ***/
$vehicle->num_doors = 2;
?>


With the properties set as above, it is now simple to use the object methods to manipulate the object by calling the methods. The methods are executed like this below.



<?php
/*** call the showPrice method ***/
$vehicle->showPrice();
/*** call the numDoors method ***/
$vehicle->numDoors();
/*** drive the vehicle ***/
$vehicle->drive();
?>


So, thats the step-by-step of your first class. You see how easy it would be now to create a new car object. Perhaps a Red Ferrari with 4 doors costing $250,000.00.



Commenting Code



In the previous sections you have seen comments for almost every line of code. This is a good practice, although some may find it excessive, as it may not be you who has to edit the code next time. OOP can get very abstracted and if you are not careful it is easy to lose site of your programmatical work flow. Most methods within a class will return a value, rather than echo a line of HTML code. A class method may also take one, or several, arguements. It is good practice to show what these arguements are and there types. An example follows below.



<?php
/**
* adds an array of numbers and returns the value
*
* @param array $numbers An array of numbers to add
*
* @access private
*
* @return int Returns sum of numbers
*
*/
private function sum_of_numbers($numbers){
/*** return the sum of the $numbers array ***/
return array_sum($numbers);
}
?>


The above function is rather simplistic, but shows well the commenting of code. The comments begin in a block of C type multiline comments and gives us a brief description of what it does, followed by the parameter it takes, in this case an array of numbers. It tells us that access to the function is private (more on this in the next section). Finally the comment block tells us that the return value is of type INT. We can also see within the function itself a single line comment just to show what is happening within the funtion itself. If you follow these practices you code will always be readable and easy to follow by yourself and others.



Inheritance (Extending a class)



Probably the greatest feature of the PHP OOP model is Inheritence. Inheritence is the ability of php to extend classes (child classes) that inherit the charactaristics of the parent class. The resulting object of an extend class has all the charactaristics of the parent class, plus whatever is in the new child, or extended class. In this instance we will extend the vehicle class and add a motorcyle. A motorcycle is still a vehicle and shares many of the same attributes such as price, drive etc. But a motorcycle has some unique features that a car does not.



Rather than type out the whole of the vehicle class definition again, we will save it in a file of its own called vehicle.class.php. It is important here to note the naming convention here as it will be important later in this tutorial. Lets see how it works.







<?php
/*** include the vehicle class definition ***/
include('vehicle.class.php');
class motorcycle extends vehicle{
/*** the number of side cars ***/
private $num_sidecars;
private $handlebars;
/**
*
* set the type of handlebars
*
* @access public
*
* @param string
*
* @return string
*
**/
public function setHandlebars($handlebarType){
$this->handlebars=$handlebarType;
}
/**
*
* Set number of side cars
*
* @access public
*
* @param int
*
* @return int
*
**/
public function setSidecar($numSidecars){
$this->numSidecars = $numSidecars;
}
/**
*
* Show the numbers of sidecars
*
* @return string
*
**/
public function showSideCar(){
echo 'This motorcyle has '. $this->numSidecars.' sidecar<br />';
}
} /*** end of class ***/
/*** our userland code ***/
/*** create a new vehicle object ***/
$vehicle = new motorcycle;
/*** the brand of vehicle ***/
$vehicle->brand = 'Harley Davidson';
/*** the shape of vehicle ***/
$vehicle->shape = 'Sportster';
/*** the color of the vehicle ***/
$vehicle->color = 'Black';
/*** number of doors ***/
$vehicle->num_doors = 0;
/*** cost of the vehicle ***/
$vehicle->price = 25000;
/*** type of handle bars ***/
$vehicle->setHandlebars('Ape Hangers');
/*** set the sidecar ***/
$vehicle->setSidecar(1);
/*** show the vehicle brand and type ***/
echo $vehicle->brand.': '.$vehicle->shape.'<br />';
/*** call the showPrice method ***/
$vehicle->showPrice();
/*** show the sidecars ***/
$vehicle->showSideCar();
/*** drive the vehicle ***/
$vehicle->drive();
?>

You see in the motorcycle class that we have used the keyword extends to extend our vehicle class. We can then proceed to set vars in the both the parent class and the child class. The child class has inherited all the characaristics of the parent vehicle class.



If you run the above code with out including the parent class, you will get a Fatal Error like this:

Fatal error: Class 'vehicle' not found in /www/oop.php on line 3



You MUST include the class definition on *every page* when you store an object


This means when you use an object or wish to extend from it. you must include the class file. Either as code, or most commonly, with an include() statement.



Visibility (public, private, protected)



The visibility of class members, (properties, methods), relates to how that member may be manipulated within, or from outside the class. Three levels of visibilty exist for class members.




  • public


  • private


  • protected



By default, all class members are public. This means if you do not declare a property or method within the class, it will be public. It is good practice to declare the visibility of class members for the sake of readability for yourself and others. It is much easier for another programmer to see your intentions. This will also future proof your scripts should access modifiers be deprecated.



Public class members (properties and methods) are available through-out the script and may be accessed from outside the class as we demonstrated in our car class. Lets create a simple new class to demonstrate.







<?php
class mathematics{
/*** a number ***/
public $num;
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
return $this->num+2;
}
}/*** end of class ***/
/*** Instantiate a new class instance ***/
$math = new mathematics;
/*** set the value of the number ***/
$math->num = 2;
/*** call the addTwo method ***/
echo $math->addTwo();
?>



We can see in the above example that the public variable $num is set from user space and we call a public method that adds two the number and returns the value of $num+2. Having our properties (variables) visible, or accessible from any part of our script works in our favour here, but it can also work against us. A could arise if we lost track of our values and changed the value of $num. To counter this problem we can create a method to set the value for us. Even with this in place it is still possible for somebody to simply access the $num variable. So we make the variable private. This ensures us that the property is only available within the class itself. It is private to the calling class. Consider the following code.







<?php
class mathematics{
/*** a number ***/
private $num;
/**
*
* Set the value of $num
*
* @access public
*
* @param $num The number to set
*
* @return int
*
**/
public function setNum($num){
$this->num = $num;
}
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
return $this->num+2;
}
}/*** end of class ***/
/*** Instantiate a new class instance ***/
$math = new mathematics;
/*** set the value of the number ***/
$math->setNum(2);
/*** call the addTwo method ***/
echo $math->addTwo();
?>
?>



Any further attempt to reset the $num property without the setNum() method would result in a Fatal Error such as

Fatal error: Cannot access private property mathematics::$num in /www/mathematics.class.php on line 43


Even if you were to try to access the private $num property from a child class it would fail. This is because private methods and properties in a parent class are not visible to child classes and cannot be accessed. To access a parent method or property from a child class you need to use the protected keyword. Like the private keyword, protetected methods and properties are available only to the class that created them. But unlike private, protected methods and properties are visible from a parent class. Lets see how this works.



<?php
class mathematics{
/*** a number ***/
protected $num;
/**
*
* Set the value of $num
*
* @access public
*
* @param $num The number to set
*
* @return int
*
**/
public function setNum($num){
$this->num = $num;
}
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
return $this->num+2;
}
}/*** end of class ***/
class divide extends mathematics{
/**
*
* Divide a number by two
*
* @access public
*
* @return int
*
**/
public function divideByTwo(){
/*** divide number by two ***/
$new_num = $this->num/2;
/*** return the new number and round to 2 decimal places ***/
return round($new_num, 2);
}
} /*** end of class ***/
/*** Instantiate a new class instance ***/
$math = new divide;
/*** set the value of the number ***/
$math->setNum(14);
echo $math->divideByTwo();
?>


We can see here the the user space code has called the setNum() method in the parent mathematics class. This method, in turn, sets the $num property. We are able to do this because the $num property has been declared protected and is visible to the child class.



Final



As we saw in the previous section there are ways to protect your code from being used in an improper manner. Another way of protecting yourself is the Final keyword. Any method or class that is declared as Final cannot be overridden or inherited by another class. Lets put it to the test.



<?php
final class mathematics{
} /*** end of class ***/
class divide extends mathematics{
}
?>


By running the above code you will get an error such as

Fatal error: Class divide may not inherit from final class (mathematics) in /www/final.php on line 8


This can protect us from those who wish to use our code for a purpose other than that for which it was intended.



Abstract Classes



An abstract class is a class that cannot be instantiated on its own. You cannot create a new object from it. To see this lets make a basic class.



<?php
abstract class mathematics{
/**
*
* Add two to a number
*
* @access public
*
* @return int
*
**/
public function addTwo(){
return $this->num+2;
}
} /*** end of class ***/
/*** try to create new object from the mathematics class ***/
$math = new mathematics
?>


Using the code above, you will get an error something like this

Fatal error: Cannot instantiate abstract class mathematics in /www/abstract.php on line 23.


As you can see, this is not allowed. Also if you declare any class method to be abstract, you must also declare the class itself as abstract too. So, whats the point you ask? Well, you can inherit from an abstract class. Any class that extends an abstract parent class must create an interface of the parent abstract methods. If this is not done a fatal error is generated. This ensures that the implementation is correct.



<?php
abstract class mathematics{
/*** child class must define these methods ***/
abstract protected function getMessage();
abstract protected function addTwo($num1);
/**
*
* method common to both classes
*
**/
public function showMessage() {
echo $this->getMessage();
}
} /*** end of class ***/
class myMath extends mathematics{
/**
*
* Prefix to the answer
*
* @return string
*
**/
protected function getMessage(){
return "The anwser is: ";
}
/**
*
* add two to a number
*
* @access public
*
* @param $num1 A number to be added to
*
* @return int
*
**/
public function addTwo($num1) {
return $num1+2;
}
} /*** end of class ***/
/*** a new instance of myMath ***/
$myMath = new myMath;
/*** show the message ***/
$myMath->showMessage();
/*** do the math ***/
echo $myMath->addTwo(4);
?>


Static Methods and Properties



The use of the static keyword allows class members (methods and properties) to be used without needing to instantiate a new instance of the class. The static declaratin must come after the visibility declaration, eg:

public static myClass{


Because there is no object created when using a static call, the keyword $this and the arrow operator, -> are not available. Static variables belong to the class itself and not to any object of that class. To access withing the class itself you need to use the self keyword along with the :: scope resolution operator. Lets whip up a quick example of using static.



<?php
/*** a simple class ***/
class myClass{
/*** a static variable ***/
static $foo;
}
/** give the static variable a value ***/
myClass::$foo = 'Bar';
/*** echo the static variable ***/
echo (myClass::$foo ).
?>


The above snippet will echo

Bar


This is rather basic as an example, so lets use something practical. Static properties are often used as counters. Here we will use a basic counter class.



<?php
class counter{
/*** our count variable ***/
private static $count = 0;
/**
* Constructor, duh
**/
function __construct() {
self::$count++;
}
/**
*
* get the current count
*
* @access public
*
* @return int
*
**/
public static function getCount() {
return self::$count;
}
} /*** end of class ***/
/*** create a new instance ***/
$count = new counter();
/*** get the count ***/
echo counter::getCount() . '<br />';
/*** create another instance ***/
$next = new counter();
/*** echo the new count ***/
echo counter::getCount().'<br />';
/*** and a third instance ***/
$third = new counter;
echo counter::getCount().'<br />';
?>


Hopefully by the end of the above snippet you can see what is happening. At each new instance the counter class we increment by one. Not also the use of the :: scope resolution operator and self keyword to refer to the static variable within the class itself.



Interfaces



Interfaces in PHP allow you to define a common structure for your classes. An interface cannot be instantiated on its own. One of the goals of OOP is re-use of code. Interfaces make this a much easier process. The interface methods have no internal logic, they are simply a "mapping" or constraint of what the class, or classes, should implement. Here we will demonstrate how this works using our vehicle class from earlier, with the addition of a stop() function.



<?php
class vehicle implements testdrive{
/*** define public properties ***/
/*** the color of the vehicle ***/
public $color;
/*** the number of doors ***/
public $num_doors;
/*** the price of the vehicle ***/
public $price;
/*** the shape of the vehicle ***/
public $shape;
/*** the brand of vehicle ***/
public $brand;
/*** the constructor ***/
public function __construct(){
echo 'About this Vehicle.<br />';
}
/*** define some public methods ***/
/*** a method to show the vehicle price ***/
public function showPrice(){
echo 'This vehicle costs '.$this->price.'.<br />';
}
/*** a method to show the number of doors ***/
public function numDoors(){
echo 'This vehicle has '.$this->num_doors.' doors.<br />';
}
/*** method to drive the vehicle ***/
public function drive(){
echo 'VRRROOOOOOM!!!';
}
/**
* a method to stop the car
*
* @access public
*
**/
public function stop(){
echo 'SSSCCRRREEEEEECCHH!!!<br />';
}
} /*** end of class ***/
/*** declare our interface ***/
interface testdrive{
/*** some functions that must be implemented ***/
function drive();
function stop();
}
/*** an new vehicle object ***/
$object = new vehicle;
/*** call some methods ***/
$object->drive();
$object->stop();
?>


You may of course create multiple classes to implement your interface, but they will not inherit from each other. When you inherit from a parent class, you may choose to override some of parent methods. If you had multiple parent class methods with the same name, but different functionality or charactaristics, PHP would have no way of telling which of these methods to use. This is why multiple inheritance does not work in PHP. In contrast, classes that implement an interface, must implement every method so there is no ambiguity.



In the real world interfaces provide us with the tools harness parts of multiple classes. Consider this scenario. If we had two classes, one for a fax and the other for a printer. Each has seperate uses and could be described like this:







<?php
class fax{
public function dial();
public function send();
public function recieve();
}
class printer{
public function printBlack();
public function printColor();
public function printDraft();
}
?>



Both of the above classes give the required usage for each item, but they do not take into consideration the existance of a printer/fax machine. To get the usage of both classes we would do something like this:




<?php
class fax{
public function dial();
public function send();
public function recieve();
}
class printer extends fax{
public function printBlack();
public function printColor();
public function printDraft();
public function kick();
}
class printerFax extends fax{
}
$object = new printerFax;
?>


This code works by creating a stack of classes. The grandparent class is fax. Then the printer class extends the fax class and inherits all the methods from that class. This is where some problems may arise. The printer class now has the function dial() available to it which is clearly going to cause some confusion and possibly errors in logic.



To counter this problem an interface can be used to tell the classes what functions (methods) are required. Lets look at the design.







<?php
interface fax{
public function dial();
public function send();
public function recieve();
}
interface printer{
public function printBlack();
public function printColor();
public function printDraft();
public function kick();
}
class printerFax implements fax, printer{
public function dial(){ }
public function send(){ }
public function recieve(){ }
public function printBlack(){ }
public function printColor(){ }
public function printDraft(){ }
public function kick(){ }
}
$object = new printerFax;
?>



Before we go further, it is recommended you run the above code. It will produce no output but we need to be sure all is well. Having run the code, remove the line

public function kick(){ }


and run it again. What you should now get is an error such as:


Fatal error: Class printerFax contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (printer::kick) in /www/oop.php on line 22



With the kick() function removed from our implementation, we have essentially broken the contract that says we will implement every function (method) specified in the interface. We can gather these functions fractionally from multiple classes, but we MUST have them all or we will get errors such as the one above.



Interfaces play a major role in with SPL and it is recommend you implement the interfaces from SPL and not just the class methods.



PHP Class functions



PHP has available several class functions to help you through the OOP mine field.




  • get_declared_interfaces()


  • class_exists()


  • get_class()


  • get_declared_classes()



Each of these is shown here beginning with the get_declared_interfaces().



get_declared_interfaces()



This helper function provides an array of all the available declared interfaces.




<?php
interface fax{
public function dial();
public function send();
public function recieve();
}
interface printer{
public function printBlack();
public function printColor();
public function printDraft();
public function kick();
}
/*** our interface implementation ***/
class printerFax implements fax, printer{
public function dial(){ }
public function send(){ }
public function recieve(){ }
public function printBlack(){ }
public function printColor(){ }
public function printDraft(){ }
public function kick(){ }
}
/*** create and printerfax object ***/
$object = new printerFax;
/*** get the declared interfaces ***/
foreach(get_declared_interfaces() as $key=>$interface)
{
echo $key.' => '.$interface.'<br />';
}
?>


The above code should produce a list such as this:




  • 0 => Traversable


  • 1 => IteratorAggregate


  • 2 => Iterator


  • 3 => ArrayAccess


  • 4 => Serializable


  • 5 => RecursiveIterator


  • 6 => OuterIterator


  • 7 => SeekableIterator


  • 8 => Countable


  • 9 => SplObserver


  • 10 => SplSubject


  • 11 => Reflector


  • 12 => fax


  • 13 => printer



From the list above you can see the SPL interfaces available and at the bottom is our fax and printer interfaces. The printerfax is not listed as it is not an interface, rather it is an implentation of an interface.



Other functions



Here we will see three helper functions for our classes




  • get_class()


  • class_exists()


  • get_declared_classes




<?php
/*** a pretend class ***/
class fax{
public function dial(){ }
public function send(){ }
public function recieve(){ }
}
/*** another pretend class ***/
class printer{
public function printBlack(){ }
public function printColor(){ }
public function printDraft(){ }
public function kick(){ }
}
/*** create an instance of the fax class ***/
$foo = new fax;
/*** create an instance of the printer class ***/
$bar = new printer;
echo '$foo is from the ' get_class($foo).' class<br />';
echo class_exists("printer").'<br />';
echo 'Declared classes are:<br /> ';
foreach(get_declared_classes() as $key=>$classname)
{
echo $key.' -> '.$classname.'<br />';
}
?>


The little snippet above will produce over one hundred available classes, shortened here for the sake of sanity, such as these below. Note our fax and printer classes at the bottom of the list.




  • $foo is from the fax class


  • 0 -> stdClass


  • 1 -> Exception


  • ---8<--- snip ---


  • 106 -> fax


  • 107 -> printer



Autoload



Earlier in this tutorial we stated that the class definition must be included in every call to an object. This is commonly achieved with the include() or require() functions such as below.





<?php
/*** include our class definitions ***/
include('classes/vehicle.class.php');
include('classes/motorcycle.class.php');
include('classes/printer.class.php');
include('classes/printer.class.php');
/*** instantiate a new vehicle class object ***/
$vehicle = new vehicle;
*** instantiate a new motorcycle class object ***/
$bike = new motorcycle;
*** instantiate a new printer class object ***/
$printer = new printer;
*** instantiate a new fax class object ***/
$fax = new fax;
?>

As you can see, this is quite cumbersome. The solution to this sort of mess is __autoload(). The __autoload() function will internally search out the class and load its definition. So the above block of code could be reduced to this.







<?php
/*** Autoload class files ***/
function __autoload($class){
require('classes/' . strtolower($class) . '.class.php');
}
/*** instantiate a new vehicle class object ***/
$vehicle = new vehicle;
/*** instantiate a new motorcycle class object ***/
$bike = new motorcycle;
/*** instantiate a new printer class object ***/
$printer = new printer;
/*** instantiate a new fax class object ***/
$fax = new fax;
?>



Now we can load up as many class definitions as we like because they will be autoloaded when we try to use a class that has not been defined. This can save much coding and much searching for code. It is important to remember the naming convention of your classes and class files. Each class file should be named the same as the class definition itself. eg: a class definition file named fax would have the filename fax.class.php



The use of the strtolower() function assures compatibility of naming conventions as windows machines fail to be case sensitive for filenames.



Serializing Objects



We have seen a lot of code above for the use of objects and how they can save us time (and $$$) by re-using them. But what if we needed to somehow store an object for later retrieval, perhaps in a database or in a session variable? PHP has given us the serialize() function to make this rather effortless. There are some limitations, but this can be a very useful tool for applications. Lets see how it performs with a little code.







<?php
/*** code here ***/
?>





Overloading



Comes a time in every programmers life when...hmm

Overloading in PHP has caused much confusion for no real reason. PHP Overloading can be broken downinto two basic components




  • Method overloading


  • Property overloading



Simply put, Method Overloading is achieved by a special function named __call(). It is available as a sort of method wildcard for calls to undefined methods within a class. This special function is only called when the original method name does not exist. The __call() will only work when the class method you are trying to access does not exist. Lets take it for a spin..







<?php
class my_class{
public function foo() {
return "This is the foo function";
}
} /*** end of class ***/
/*** create a new class object ***/
$obj = new my_class;
/*** call a non-existant method ***/
$obj->bar();
?>





Of course the above snippet of code will produce an error such as

Fatal error: Call to undefined method my_class::bar() in /www/overload.php on line 12


because we have called the bar() class method that does not exist. Enter __call(). With the __call() function in place, PHP will try to create the function and you have any code within the _call() method that you like. The __call() method takes two arguements, the method name, and the arguements. Your call to the undefined method may have many arguements and these are returned in an array. Lets put it to the test with two args.







<?php
class my_class{
public function foo() {
return "This is the foo function";
}
/*** __call() method with two args ***/
public function __call($method, $arg){
echo $method.'<br />';
print_r($arg);
}
} /*** end of class ***/
/*** create a new class object ***/
$obj = new my_class;
/*** call a non-existant method ***/
$obj->bar("arg1", "arg2");
?>



The above code will print the following

bar


Array ( [0] => arg1 [1] => arg2 )


The __call() method has returned the method name that we called along with the array of args passed to it.



Lets now look at we can dynimically manipulate or overload our data.




<?php
class readyGetSet {
/*** declare $item ***/
private $item = 'Skate Board';
/*** declare the price ***/
private $price = 100;
/*** our call function ***/
function __call($method, $arguments){
/*** set property and prefix ***/
$prefix = strtolower(substr($method, 0, 3));
$property = strtolower(substr($method, 3));
if (empty($prefix) || empty($property))
{
return;
}
if ($prefix == 'get' && isset($this->$property))
{
return $this->$property;
}
if ($prefix == 'set')
{
$this->$property = $arguments[0];
}
}
}
$obj = new readyGetSet;
echo 'Item: ' . $obj->getItem() . '<br />';
echo 'Price: ' . $obj->getPrice() . '<br />';
$obj->setItem('CD');
$obj->setPrice(25);
echo 'Item: ' . $obj->getItem() . '<br />';
echo 'Price: ' . $obj->getPrice() . '<br />';
?>


The second part of overloading refers to properties and the ability to be able to dynamically get and set object properties. The __get() function is called when reading the value of an undefined property, and __set() is called when trying to change that properties value. I hope this is clear as it can get a little confusing... Lets see how it works by example.







<?php
class candy{
/*** declare a property ***/
public $type='chocolate';
/*** a normal method ***/
public function wrap(){
echo 'Its a wrap';
}
/*** our __set() function ***/
public function __set($index, $value){
echo 'The value of '.$index.' is '.$value;
}
} /*** end of class ***/
/*** a new candy object ***/
$candy = new candy;
/*** set a non existant property ***/
$candy->bar = 'Blue Smarties';
?>





The result from above will be:

The value of bar is Blue Smarties


Lets see what we have done. We have described a class named candy which contains a public property named $type. It has a simple method and our __set() method. After the class our user code creates a new instance of the candy class. Then we try to set a variable that does not exist in the class. Here the __set method takes control and assigns it for us. We then see in our __set method that it echoes the name of the variable, plus its intended value. The __set() method takes two arguements, the name of the non existant variable, and its intended value.



The __get() method ....







<?php
class candy{
/*** declare a property ***/
public $type='chocolate';
public $choctype = array('milk'=>0, 'dark'=>1, 'plain'=>2);
/*** a normal method ***/
public function wrap(){
echo 'Its a wrap';
}
/*** our __set() function ***/
public function __get($index){
echo 'Retrieving element of $choctype property with index of '.$index.'<br />';
return $this->choctype[$index];
}
} /*** end of class ***/
/*** a new candy object ***/
$candy = new candy;
/*** set a non existant property ***/
echo 'The value of the following element property is '.$candy->milk;
?>

From the above code we get the result


Retrieving element of $choctype property with index of milk


The value of the following element property is 0



Class Constants



You have more than likely seen the use standard constants in PHP. To define a standard constant we use this code:




/*** define an error message ***/
define('_ERROR_MSG', 'An Error has occured!');
/*** echo the constant ***/
echo _ERROR_MSG;
?>


The above snippit would output

An Error has occured!



To define a class constant we use the const keyword.





<?php
class my_class {
/*** define a class constant ***/
const _ERROR_MSG = 'An Error has occured!';
public function show(){
echo self::_ERROR_MSG;
}
} /*** end of class ***/
?>

There are now three ways the class constant can be access from this example.



<?php
/*** static call to constant ***/
echo my_class::_ERROR_MSG;
/*** instantiate a class object ***/
$my_class = new my_class;
/*** can run the show() method ***/
$my_class->show();
/*** static call to the show method() ***/
my_class::show();
?>


Each of the above methods would output the same line

An Error has occured!


A class constant, like standard constants, must be exactly as the name suggests, a constant value. It cannot be a variable or the result of a function or method.