Kategori
PHP

Efficient Code using PHP Include

Discussion Board : Using PHP Include code to make listings more efficiently.
Requirements: Webserver Package, already installed.

INCLUDE, generally used for the php code that will be frequently used, means that the code which will often be written repeatedly in building applications or any coding in PHP.

Why using Include ?
1. It would be very inefficient if we must write the same code repeatedly.
2. If it were the case there are parts of the code that must be changed, then, once again, be very inefficient if you need to change the wrong one by one.

And once again, this will be very redundant and time-consuming and lead to potential human error. By using include, the problem – this problem can be overcome.

Does it Include?
PHP file include is inserted in another PHP file, generally include contain information that will repeatedly be used in other code. For example, if you want to build the site navigation to be displayed in every page of your site, then you simply write the code navigation is in one file for later to include it in every page of the site.

Case Studies : Using Include for Header and Footer.

1. Create a header.
Suppose we want to display today’s date as a header. Type the following script.

[sourcecode language=”php”]
<?php
echo "This is a HEADER, And ";
echo "Today is ";
echo date("F d");
echo ", ";
echo date("Y");
?>
[/sourcecode]

Code date The above will display today’s date. Save the script above with the name of header.php.

2. Creating a footer.
For example we will display the copyright as a footer to our site. Type the script below.

[sourcecode language=”php”]
<?php
echo "Copyright by itx.web.id";
?>
[/sourcecode]

Save the script above with the name footer.php

3. Placing the header and footer in the page.
Type the following script.

[sourcecode language=”php”]
<?php
include "header.php";
echo "<h1> This is the BODY of site !</h1>";
include "footer.php";
?>
[/sourcecode]

Suppose we want to put the header at the top page, then the code to header.php must diinclude weight on the code as well (on body). Similarly for the footers, because it is located at the bottom of the page, then the code is also placed at the bottom footer.php code.

4. The result?
Run body.php, it will display the picture as follows.

p.s. OHYA, save ALL the php file in the one – same folder. Ok, haapy cooding yah πŸ˜€

Kategori
PHP

Efisien Code Menggunakan PHP Include

Discussion Board : Menggunakan Include untuk membuat listing code PHP lebih efisien.
Kebutuhan : Webserver Package, already installed.

INCLUDE, pada umumnya digunakan untuk code php yang akan sering digunakan, maksudnya adalah code yang akan sering ditulis berulangkali dalam membangun aplikasi atau coding apapun dalam PHP.

Kenapa menggunakan Include ?
1. Akan sangat tidak efisien apabila kita harus menulis code yang sama tersebut berulang kali.
2. Apabila terjadi kasus ada bagian dari code tersebut yang harus diubah, maka, sekali lagi, akan sangat tidak efisien apabila anda harus mengubah bagian yang salah tersebut satu per satu.

Dan sekali lagi, hal ini akan sangat redundant dan menghabiskan waktu serta memicu potensi terjadinya human error. Dengan menggunakan include, masalah – masalah diatas dapat diatasi.

Apakah Include itu?
Include adalah file PHP yang diselipkan dalam file PHP yang lain, pada umumnya include mengandung informasi yang akan berulangkali digunakan dalam code yang lain. Sebagai contoh, apabila anda ingin membangun navigasi situs yang harus ditampilkan dalam setiap halaman situs anda, maka anda cukup menulis code navigasi tersebut dalam satu file untuk kemudian meng-include nya dalam setiap halaman situs tersebut.

Studi Kasus : Menggunakan Include untuk Header dan Footer.

1. Membuat header.
Misalkan kita ingin menampilkan tanggal hari ini sebagai header. Ketikkan script dibawah ini.

[sourcecode language=”php”]
<?php
echo "This is a HEADER, And ";
echo "Today is ";
echo date("F d");
echo ", ";
echo date("Y");
?>
[/sourcecode]

Code date diatas akan menampilkan tanggal hari ini. Simpan script diatas dengan nama header.php.

2. Membuat footer.
Misalnya kita akan menampilkan copyright sebagai footer untuk situs kita. Ketikkan script dibawah.

[sourcecode language=”php”]
<?php
echo "Copyright by itx.web.id";
?>
[/sourcecode]

Simpan script diatas dengan nama footer.php

3. Menempatkan header dan footer dalam halaman situs.
Ketikkan script berikut.

[sourcecode language=”php”]
<?php
include "header.php";
echo "<h1> This is the BODY of site !</h1>";
include "footer.php";
?>
[/sourcecode]

Misalkan kita ingin menempatkan header dibagian atas halaman situs, maka code untuk header.php harus diinclude dibagian atas code juga (diatas body). Begitu juga untuk footer, karena terletak dibagian bawah halaman, maka code footer.php juga ditempatkan dibagian bawah code.

4. Hasilnya?
Jalankan body.php, maka akan ditampilkan gambar seperti berikut.

p.s. OHYA, simpan semua file php diatas dalam satu folder. Ok, haapy cooding yah πŸ˜€

Kategori
PHP

Passing variables between pages in PHP with URL and Session

Case Studies : Passing variables between pages in PHP with PHP Session.
Needs : Webserver package, already installed .

For the case this time, assume that you will make the application logged on to the page – next page after the user is logged in, you want to continue to greet the user. Of course, you must store the variable name of the user right? Basically, there are four ways to do this, namely:
1. Pass the variable in the URL.
2. Through Session.
3. Via Cookie and,
4. With HTML Form.

This tutorial will discuss about the point to one and two of the four ways above, ie pass the variable through a combination of URL and Session.

1. Type the following script (named script1.php).

[sourcecode language=”php”]
<?php
session_start();
$_SESSION[‘username’] = "June";
?>
<html>
<head>
<TITLE>Just A Sample – ITX.WEB.ID</TITLE>
</head>
<body>
<?php
$mybook = "My Name is June";
echo "<a href=’mybook.php?book=$mybook’>";
echo "Click here to see your book!";
echo "</a>";
?>
</body>
</html>
[/sourcecode]

Note that in the script above, we assign a username variable manually (assumption: that the user has been logged and the username is saved in the session). So, how to store value in session is with the following syntax:
$_SESSION['username'] = "June";

Meanwhile, variable book will be passed through the URL. Its syntax is as follows:
mybook.php? book = $mybook , with variable mybook has been assigned previously.

Once executed, the script above will output the following :
Click here to see your book!

2. Type the following script (save it as mybook.php). The following script is the script from the script output link 1 above. This script will read a variable that has dilewat through URL and Session.

[sourcecode language=”php”]
<?php
session_start();
echo "<h2> Welcome to your Book, ";
echo $_SESSION[‘username’];
echo "! </h2> <br>";
echo "Your favorite book is ";
echo $_REQUEST[‘book’];
echo "<br>";
?>
[/sourcecode]

Note the section above. From script1.php, we know that we have missed 2 variables, namely variable book and variable username , with each – each value is My Name is June for variable book , and June for the variable username.

Then I read the second variable is:
1. Reading the variable book (which is passed via the URL): $_REQUEST ['book'] .
2. Reading the variable username (which is passed via Session): $_SESSION ['username'] .

Click the link generated script1.php, then you will be redirected to the script page 2 (mybook.php), with a view like the picture below.

Haaaapy Coding πŸ˜€

Kategori
PHP

Melewatkan Variable antar Halaman PHP dengan URL dan Session

Studi Kasus : Melewatkan variable antar halaman dalam PHP dengan PHP Session.
Kebutuhan : Webserver Package, already installed.

Untuk kasus kali ini, asumsikan bahwa anda akan membuat aplikasi login dimana untuk halaman – halaman berikutnya setelah user tersebut login, anda ingin terus menyapa user tersebut. Tentu saja, anda harus menyimpan variable nama dari user tersebut kan? Pada dasarnya, terdapat empat cara untuk melakukan hal ini, yaitu :
1. Melewatkan variable dalam URL.
2. Melalui Session.
3. Via Cookie dan,
4. Dengan HTML Form.

Tutorial kali ini akan membahas mengenai point ke satu dan dua dari empat cara diatas, yaitu melewatkan variable melalui gabungan dari URL dan Session.

1. Ketikkan script dibawah ini (namai script1.php).

[sourcecode language=”php”]
<?php
session_start();
$_SESSION[‘username’] = "June";
?>
<html>
<head>
<TITLE>Just A Sample – ITX.WEB.ID</TITLE>
</head>
<body>
<?php
$mybook = "My Name is June";
echo "<a href=’mybook.php?book=$mybook’>";
echo "Click here to see your book!";
echo "</a>";
?>
</body>
</html>
[/sourcecode]

Perhatikan bahwa dalam script diatas, variable username kita assign secara manual (asumsi : bahwa user telah login dan username telah disimpan dalam session). Jadi, cara untuk menyimpan value dalam session adalah dengan syntax berikut :
$_SESSION['username'] = "June";

Sedangkan, variable book akan dilewatkan melalui URL. Syntax nya adalah sebagai berikut :
mybook.php?book=$mybook, dengan variable mybook telah diassign sebelumnya.

Setelah dijalankan, script diatas akan memberikan output sebagai berikut :
Click here to see your book!

2. Ketikkan script berikut (simpan dengan nama mybook.php). Script berikut adalah script dari link output script 1 diatas. Script ini yang akan membaca variable yang telah dilewat melalui URL dan Session.

[sourcecode language=”php”]
<?php
session_start();
echo "<h2> Welcome to your Book, ";
echo $_SESSION[‘username’];
echo "! </h2> <br>";
echo "Your favorite book is ";
echo $_REQUEST[‘book’];
echo "<br>";
?>
[/sourcecode]

Perhatikan bagian diatas. Dari script1.php, kita tahu bahwa kita telah melewatkan 2 buah variable, yaitu variable book dan variable username, dengan masing – masing value nya adalah My Name is June untuk variable book, dan June untuk variable username.
Maka cara membaca kedua variable tersebut adalah :
1. Membaca variable book (yang dilewatkan via URL) : $_REQUEST['book'].
2. Membaca variable username (yang dilewatkan via Session) : $_SESSION['username'].

Klik link yang dihasilkan script1.php, maka anda akan diarahkan ke halaman script 2 (mybook.php), dengan tampilan seperti gambar dibawah ini.

Haaaapy Coding πŸ˜€

Kategori
WordPress

Set Metadata in the WordPress Manually

Discussion Board : Create metadata tag in the WordPress manually with Add Custom Field features.
Requirements : WordPress bundle, already installed, because this tutorial we will practice in our local website (or for those of you who have hosting with wordpress cms, can be practicing in your hosting)

If you have to scroll down the page your WordPress post, you will find the menu “Add custom field”, with a brief description follows:

Custom fields can be used to add extra metadata to a post that you can use in your theme.

Before we discuss much about how to tag metadata, in fact, whether these metadata tags?

metadata tags are html tags that are at the head area in a page html page . tags are metadata that is useful in general is description , or keywords , which explains about a site, because the common definition of metadata is “data about data “. Metadata is commonly used by search engines such as Google or Yahoo to index your site pages.

When we do a post on WordPress, the metadata tags will not be found on our web page. Why? Because the metadata is actually determined by the author (the author of the article, simply because the author is most knowledgeable about what he wrote in the article, so only the author of the most appropriate in describing the keyword or description about the page.) WordPress can not read the mind of a author. One way to provide metadata tags in WordPress is done with Add Custom Field .

Ok, How do I? For this case study, we will try to create metadata for keywords .

1. Login in your wordpress.
2. Go to the Post – Add New Post pages.
3. Scroll down till you find the Custom Field menu.
4. Choose “Add Custom Field.”button. Type “keywords” on the name, and fill “wordpress, metadata, seo” in the value (this value is just a sample, the mean is the keywords for the articles that was writen.)

5. Click Add Custom Field to save.
6. For the next post, you do not need to create a Custom Field again if you want to use metadata tag keywords, you just choose to using the last field you have created, like the picture below.

After you successfully add custom fields in WordPress, just how We see the metadata tags that have been created on our themes. Time for The trick.

1. Find a file called functions.php which is located in your WordPress root directory (wp-content>> themes>> name of your themes>> functions.php). Add this script below in the functions.php file.

[sourcecode language=”php”]
function set_keywords(){
global $post;
$keywords = get_post_meta($post->ID, ‘keywords’, true);
$default_keywords = ‘keywords, default, up, to, you’;
$metatag= "";

if (empty($keywords)){
$keywords = $default_keywords;
}
if (is_home() || is_front_page()){
$keywords = $default_keywords;
}

$metatag="\t";
$metatag.= "<meta name=\"keywords\" content=\" ";
$metatag.= $keywords;
$metatag.= "\" />";
$metatag.= "\n\n";

echo $metatag;
}
add_action(‘wp_head’, ‘set_keywords’);
[/sourcecode]

Happy WordPress-ing ! πŸ˜€

Kategori
WordPress

Set Metadata dalam WordPress secara Manual

Discussion Board : Membuat tag metadata dalam WordPress secara manual dengan Add Custom Field.
Requirements : WordPress bundle, already installed, karena kita akan mempraktikkan tutorial ini dalam web lokal kita (atau untuk anda yang memiliki hosting dengan cms wordpress, bisa mempraktekkannya di hosting anda)

Kalau anda men-scroll halaman posting WordPress anda kebawah, anda akan menemukan menu “Add custom field”, dengan deskripsi singkat berikut :

Custom fields can be used to add extra metadata to a post that you can use in your theme.

Sebelum kita membahas jauh mengenai cara memberi tag metadata, sebenarnya, apakah tag metadata tersebut?

Tag metadata adalah tag html yang berada pada area head dalam halaman html suatu page. Tag metadata yang cukup berguna pada umumnya adalah description, atau keyword yang menjelaskan mengenai suatu situs tersebut, karena definisi umum dari metadata adalah “data about data”. Metadata ini pada umumnya digunakan oleh search engine seperti Google atau Yahoo untuk meng-index halaman situs anda.

Ketika kita melakukan posting pada WordPress, tag metadata tidak akan ditemukan pada halaman situs kita. Kenapa? Karena sebenarnya metadata ditentukan sendiri oleh si author (penulis artikel tersebut, simply, karena si author adalah yang paling tahu mengenai apa yang ia tulis dalam artikel tersebut, jadi hanya si author yang paling tepat dalam mendeskripsikan keyword atau description mengenai page tersebut). WordPress tidak dapat membaca pikiran seorang author. Salah satu cara memberikan tag metadata pada WordPress adalah dilakukan dengan Add Custom Field.

Ok, Bagaimana caranya? Untuk studi kasus ini, kita akan coba membuat metadata untuk keywords.

1. Login ke halaman WordPress anda.
2. Masuk ke halaman Post – Add New Post.
3. Scroll down sampai anda menemukan menu Custom Field.
4. Pilih button “Add Custom Field.” Ketikkan “keywords” pada name, dan isikan “wordpress, metadata, seo” pada value (value ini merupakan contoh saja, maksudnya adalah keywords dari artikel yang ditulis.)

5. Klik Add Custom Field untuk menyimpan.
6. Untuk postingan – postingan anda selanjutnya, tidak perlu membuat Custom Field lagi jika ingin menggunakan tag metadata dan keyword, cukup memilih dari custom field yang telah ada, seperti gambar dibawah.

Setelah anda sukses menambahkan custom field pada WordPress, tinggal bagaimana cara menampilkan tag metadata yang telah dibuat pada themes kita. Caranya?

1. Cari file bernama functions.php yang terletak dalam directory root WordPress anda (wp-content >> themes >> nama themes anda >> functions.php ).
[sourcecode language=”php”]<br />
function set_keywords(){<br />
global $post;<br />
$keywords = get_post_meta($post-&gt;ID, ‘keywords’, true);<br />
$default_keywords = ‘keywords, default, up, to, you’;<br />
$metatag= &quot;&quot;;</p>
<p> if (empty($keywords)){<br />
$keywords = $default_keywords;<br />
}<br />
if (is_home() || is_front_page()){<br />
$keywords = $default_keywords;<br />
}</p>
<p> $metatag=&quot;\t&quot;;<br />
$metatag.= &quot;&lt;meta name=\&quot;keywords\&quot; content=\&quot; &quot;;<br />
$metatag.= $keywords;<br />
$metatag.= &quot;\&quot; /&gt;&quot;;<br />
$metatag.= &quot;\n\n&quot;;</p>
<p> echo $metatag;<br />
}<br />
add_action(‘wp_head’, ‘set_keywords’);<br />
[/sourcecode]

Happy WordPress-ing ! πŸ˜€

Kategori
PHP

Regular Expression ( Regex ) with PHP

Discussion Board : Introduction to the basic concept of Regular Expression syntax in PHP, with the sample few case for using PHP Regex.
Requirement : webserver package, already installed (or just PHP with Apache).

Regex? What it is?
Regular Expression (Regex) is a concept of pattern matching (pattern matching ) within a string. In general, the regular expression used for validation (in an information system development), or used for text processing (text processing). However, sometimes regular expression also often used in Information Retrieval.

Tutorial – tutorial below will mengkover cases – cases that can be handled with Regex, for example by using the Regex pattern matching.

1. What is the pattern “instant noodle” in a string?

[sourcecode language=”php”]
$string = ‘iloveindomieverymuch’;

$isMatch = preg_match("/indomie/", $string); //here the regex

echo $isMatch;
[/sourcecode]

Script above will produce output “1” because the “indomie” pattern exist in the “iloveindomieverymuch” string.diatas akan menghasilkan output “1” karena pattern “indomie” ada dalam string “iloveindomieverymuch”. As we can see, that preg_match will produce boolean value 1 if there is string match, and 0 if not.

2. Apakah string dimulai dengan pattern “ilove” ?
For checking the begin of string, use ^ symbol.

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuch’;
isMatch = preg_match("/^ilove/", $string)

if($isMatch) {
echo ‘The string begins with ilove’; //if there’s a match
}
else {
echo ‘The string does not begin with ilove’; //if there isn’t match
}
?>
[/sourcecode]

This Script above will produce output like below,
The string begins with ilove

3. Does the string end with a pattern “much”?
$ pattern can be used, or perhaps better with as below.

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuchactually’;
isMatch = preg_match("/much\z/i", $string)

if($isMatch) {
echo ‘The string ends with much’; //if there’s a match
}
else {
echo ‘The string does not end with much’; //if there isn’t match
}
?>
[/sourcecode]

When executed, the script above will output as follows,
The string does not end with much

This is because preg_match give value 0, because the string does not meet the rules specified by regex.

4. Strings, including letters or numbers?
The script below will check whether a word including the number (number), or composed of letters (name).

[sourcecode language=”php”]
<?php
$word= ‘ALAN’;
if(preg_match("/^[A-Z]/", $word)) {
$type = ‘name’;
}
else if(preg_match("/^[0-9]/", $word)) {
$type = ‘number’;
}
echo $type;
?>
[/sourcecode]

The output that may result from the script above is as follows,
name

However, if we replace $ word above with the string “1231”, it will produce output,
number

The above tutorial only gives examples of doing a regular expression with preg_match. Of course there are others, in PHP itself to the use of regular expression can be used with functions – functions such as preg_match_all, ereg, eregi, ereg_replace, preg_replace.
… and others.

For thecheatsheet of PHP regular expression, you can go here.

Ok, Happy Coding πŸ˜€

Kategori
PHP

Regular Expression (Regex) dengan PHP

Discussion Board : Mengenal Regular Expression dalam PHP, beserta contoh – contoh kasus singkat dari penggunaan PHP Regex.
Requirement : webserver package, already installed (atau sebenarnya PHP saja sudah cukup, tanpa mysql atau apache).

Regex? What it is?
Regular Expression (Regex) adalah suatu konsep pencocokan pola (pattern matching) di dalam suatu string. Pada umumnya, regular expression digunakan untuk validasi (dalam sebuah pembangunan sistem informasi), atau digunakan untuk proses pengolahan teks (text processing). Namun, adakalanya regular expression juga sering digunakan dalam Information Retrieval.

Tutorial – tutorial dibawah ini akan mengkover kasus – kasus yang bisa ditangani dengan Regex, sebagai contoh pattern matching dengan menggunakan Regex.

1. Apakah pattern “indomie” ada dalam string?

[sourcecode language=”php”]
$string = ‘iloveindomieverymuch’;

$isMatch = preg_match("/indomie/", $string); //here the regex

echo $isMatch;
[/sourcecode]

Script diatas akan menghasilkan output “1” karena pattern “indomie” ada dalam string “iloveindomieverymuch”. Dapat dilihat, bahwa preg_match akan menghasilkan nilai boolean 1 apabila ditemukan matching, dan 0 apabila tidak ditemukan.

2. Apakah string dimulai dengan pattern “ilove” ?
Untuk pengecekan awal string, dapat digunakan simbol ^

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuch’;
isMatch = preg_match("/^ilove/", $string)

if($isMatch) {
echo ‘The string begins with ilove’; //if there’s a match
}
else {
echo ‘The string does not begin with ilove’; //if there isn’t match
}
?>
[/sourcecode]

Script diatas akan menghasilkan output seperti berikut,
The string begins with ilove

3. Apakah string diakhiri dengan pattern “much” ?
Dapat digunakan pattern $, atau mungkin lebih baik dengan seperti dibawah ini,

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuchactually’;
isMatch = preg_match("/much\z/i", $string)

if($isMatch) {
echo ‘The string ends with much’; //if there’s a match
}
else {
echo ‘The string does not end with much’; //if there isn’t match
}
?>
[/sourcecode]

Apabila dijalankan, script diatas akan memberikan output sebagai berikut,
The string does not end with much
Hal ini dikarenakan preg_match memberikan nilai 0, karena string tidak memenuhi rule yang ditetapkan dengan regex.

4. String, termasuk huruf atau angka?
Script dibawah akan mengecek apakah suatu kata termasuk number (angka), ataukah tersusun dari huruf (name).

[sourcecode language=”php”]
<?php
$word= ‘ALAN’;
if(preg_match("/^[A-Z]/", $word)) {
$type = ‘name’;
}
else if(preg_match("/^[0-9]/", $word)) {
$type = ‘number’;
}
echo $type;
?>
[/sourcecode]

Output yang mungkin dihasilkan dari script diatas adalah sebagai berikut,
name

Namun apabila kita mengganti $word diatas dengan string “1231”, maka akan dihasilkan output,
number

Tutorial diatas hanya memberikan contoh melakukan regular expression dengan preg_match. Tentu ada yang lain, dalam PHP sendiri untuk penggunaan regular expression dapat digunakan dengan fungsi – fungsi seperti preg_match_all, ereg, eregi, ereg_replace, preg_replace.
… dan lain-lain.

Untuk cheatsheet PHP regular expression, dapat dikunjungi disini.

Ok, Happy Coding πŸ˜€

Kategori
PHP

Object Oriented Programming with PHP

Discussion Board : Introduction to object oriented programming concept on the PHP, especially class and inheritance.
Requirements: webserver package, already installed.

According Wikipedia.Com, Object Oriented Programming is paradigm to object-oriented programming. All data and functions within this paradigm is wrapped in a class or object.

Key in OOP is the object. Objects can be said as a collection of variables and functions (which in OOP, the variable referred to as properties, and functions called methods) that are collected in a single entity. Methods used to manipulate data in the object, the properties are part containing information about the data.

For this tutorial we will discuss two basic concepts in OOP, namely Class , and Inheritance .

Class.
Class is a representation of the object, inside the class methods and properties have . Immediately, we create a class (save with the name student.class.php , and put all the scripts in this tutorial in a folder at the same ).

[sourcecode language=”php”]
<?php
class student {

public $name;
public $address;

/*constructor, is a function that will always be executed when an object diinstansiasi / created. If a class must perform a certain function before running the code, then this is where to put that particular function (usually to call the library). */

public function __construct(){
echo ‘Student’s Data.<br />’;
}

public function show_name {
echo ‘Student’s name is : ‘.$this->name.'<br/>’;
}

public function show_address {
echo ‘Student’s address is : ‘.$this->address.'<br/>’;
}

}
?>
[/sourcecode]

Yup, you have created a class. For using that class, we need to create, or initialize an object from that class. Now, let’s try to make an object from Student class above.

[sourcecode language=”php”]
<?php
$student1 = new student; //this create new object in the class student named object student1

//assigning data into properties
$student1->name = ‘Alan’;
$student1->address = ‘Temari Street, 15’;

//call the method
$student1->show_name();
$student1->show_address();

?>
[/sourcecode]

That above script will produce something like this one,

Student’s Data
Student’s name is : Alan
Student’s address is : Temari Street, 15

Inheritance.
Inheritance is a capability for extending some class that will inherit ALL the parent class’s character. In this case, the class that will inherit is called child class.

[sourcecode language=”php”]
<?php
include(‘student.class.php’);

class newstudent extends student {
privat $register_number;

public function show_register_number () {
echo ‘Student’s Register Number is : ‘.$this->register_number.'<br/>’;
}

}
?>
[/sourcecode]

Can be explained that the object of new students (new student) must have different properties with the object pupil (student), where for the new students have a property register_number (registration number) that is not owned by the object pupil. Meanwhile, a new student object has all the characteristics possessed by the object pupil. This is where the concept of Inheritance useful. Instead of having to create a new class for new students object, we could extend it from an existing object, that object of students, by adding properties and methods specific to the new student object.

In this case,
object student (murid) –> parent class
object newstudent (murid baru) –> child class

For using child class, you can try to use this script below,

[sourcecode language=”php”]
<?php
$student2 = new newstudent; //this create new object in the class student named object student1

//assigning data into properties
$student2->name = ‘June’;
$student2->address = ‘Kebangkitan Street, 28’;
$student2->register_number = ‘193-123-111’;

//call the method
$student1->show_name();
$student1->show_register_number();
?>
[/sourcecode]

That above script will produce something like this one,

Student’s Data
Student’s name is : June
Student’s address is : Kebangkitan Street, 28
Student’s register number is : 193-123-111

The Ends πŸ˜€ Hope that tutorial above could give basic concept for Object oriented programming with PHP, however, this tutorial -surely- still very poor for those who want to learn OOP.

Happy Coding πŸ˜€

Kategori
PHP

Pemrograman Berorientasi Object dengan PHP

Discussion Board : Mengenal konsep pemrograman berorientasi objek dalam PHP, terutama class dan inheritance.
Kebutuhan : webserver package, already installed (atau sebenarnya PHP saja sudah cukup, tanpa mysql atau apache).

Menurut Wikipedia.Com, Pemrograman Berorientasi Object adalah paradigma pemrograman yang berorientasikan kepada objek. Semua data dan fungsi di dalam paradigma ini dibungkus dalam class atau object.

Kunci dalam OOP adalah object. Object dapat dikatakan sebagai kumpulan variabel dan fungsi (yang mana dalam OOP, variabel disebut sebagai properties, dan fungsi disebut sebagai method) yang dikumpulkan dalam satu entitas. Method digunakan untuk memanipulasi data dalam object, properties adalah bagian yang mengandung informasi mengenai data tersebut.

Untuk tutorial kali ini kita akan membahas mengenai 2 konsep dasar dalam OOP, yaitu Class, dan Inheritance.

Class.
Class adalah representasi dari object, didalam class terdapat method dan properties. Langsung saja kita membuat class (simpan dengan nama student.class.php, dan letakkan semua script dalam tutorial kali ini dalam satu folder yang sama).

[sourcecode language=”php”]
<?php
class student {

public $name;
public $address;

/*constructor, adalah function yang akan selalu dijalankan ketika sebuah object diinstansiasi / diciptakan. Apabila sebuah class harus menjalankan sebuah fungsi tertentu sebelum menjalankan suatu code, maka disinilah tempat untuk menaruh fungsi tertentu tersebut (biasanya untuk memanggil library). */

public function __construct(){
echo ‘Student’s Data.<br />’;
}

public function show_name {
echo ‘Student’s name is : ‘.$this->name.'<br/>’;
}

public function show_address {
echo ‘Student’s address is : ‘.$this->address.'<br/>’;
}

}
?>
[/sourcecode]

Yup, kamu telah membuat sebuah class. Untuk bisa menggunakan class tersebut, kita perlu membuat, atau menginisialisasi sebuah object dari class tersebut. Sekarang, mari kita mencoba membuat sebuah object dari class Student diatas.

[sourcecode language=”php”]
<?php
$student1 = new student; //this create new object in the class student named object student1

//assigning data into properties
$student1->name = ‘Alan’;
$student1->address = ‘Temari Street, 15’;

//call the method
$student1->show_name();
$student1->show_address();

?>
[/sourcecode]

Script diatas akan menghasilkan output kira2 seperti ini,

Student’s Data
Student’s name is : Alan
Student’s address is : Temari Street, 15

Inheritance.
Inheritance adalah kemampuan untuk meng-extend class yang akan mewarisi semua karakter dari parent class nya. Dalam hal ini, class yang mewarisi disebut child class.

[sourcecode language=”php”]
<?php
include(‘student.class.php’);

class newstudent extends student {
privat $register_number;

public function show_register_number () {
echo ‘Student’s Register Number is : ‘.$this->register_number.'<br/>’;
}

}
?>
[/sourcecode]

Dapat dijelaskan bahwa object murid baru (new student) tentunya memiliki properti yang berbeda dengan object murid (student), dimana untuk murid baru memiliki properti register_number (nomor pendaftaran) yang tidak dimiliki oleh object murid. Sedangkan object murid baru memiliki semua karakter yang dimiliki oleh object murid. Disinilah konsep Inheritance berguna. Daripada harus membuat sebuah class baru untuk object murid baru, kita bisa meng-extend nya dari Object yang telah ada, yaitu object murid, dengan menambahkan properti dan method khusus untuk object murid baru tersebut.

Dalam kasus ini,
object student (murid) –> parent class
object newstudent (murid baru) –> child class

Untuk menggunakan child class tersebut dapat dicoba dibawah ini,

[sourcecode language=”php”]
<?php
$student2 = new newstudent; //this create new object in the class student named object student1

//assigning data into properties
$student2->name = ‘June’;
$student2->address = ‘Kebangkitan Street, 28’;
$student2->register_number = ‘193-123-111’;

//call the method
$student1->show_name();
$student1->show_register_number();
?>
[/sourcecode]

Script diatas kira-kira akan menghasilkan output seperti berikut,

Student’s Data
Student’s name is : June
Student’s address is : Kebangkitan Street, 28
Student’s register number is : 193-123-111

Sekian πŸ˜€ Semoga tutorial diatas dapat memberikan konsep dasar untuk Pemrograman berorientasi object dengan PHP, walopun -tentunya- masih sangat kurang untuk anda yang ingin mempelajari OOP.

Happy Coding πŸ˜€