PHP Cheat: Fungsi dan Kelas

influence Explorasi Basic Fungsi + Class PHP

// mendefinisikan fungsi

function getLuasLingkaran($r){
return pi() * $r * $r;
}
echo “luas lingkaran berjari2 10: ” . getLuasLingkaran(10);
//luas lingkaran berjari2 10: 314.15926535898

// menghindari duplikasi fungsi

function asalAja(){
return “exits here”;
}
echo function_exists(“asalAja”)? “Exist” : “Not”; // Exist
echo “<br>” . (function_exists(“tidakAja”)?”ada” : “tidak”); // tidak

// mengakses variabel external dari fungsi
$name = “G3n1k”;
function yes(){
global $name;
return $name;
}
echo yes(); // G3n1k

function yup(){
return $GLOBALS[‘name’];
}
echo yup(); // G3n1k

function yep(){
global $name;
echo “Nama awal: ” . $name . “<br/>”;
$name = ” Curly”;
echo “Nama akhir : ” . $name . “<br/>”;
}
echo “Sebelum fungsi: ” . $name . “<br/>”;
yep();
echo “Sesudah fungsi ” . $name . “<br/>”;
// Sebelum fungsi: G3n1k
// Nama awal: G3n1k
// Nama akhir : Curly
// Sesudah fungsi Curly

// nilai default untuk fungsi
function luas0($r, $pi=3.14″){
return $pi * $r * $r;
}
echo luas0(10). ” fungsi tanpa masukan pi<br>”;
echo luas0(10, pi()) . ” fungsi dengan PI”;
// 314 fungsi tanpa masukan pi
// 314.15926535898fungsi dengan PI

// memproses panjang-variabel daftar Argument
function someFunc() {
$numArgs = func_num_args(); // get argument passed
$args = func_get_args(); // dapatkan argument
print “you sent me the following arguments: “;
for($x = 0; $x<sizeof($args); $x++){
print “<br> Aguments $x :” ;
if(is_array($args[$x])) {
print ” ARRAY “;
foreach ($args[$x] as $index=>$element) {
print ” $index => $element “;
}
} else {
print ” $args[$x] “;
}
}
}
someFunc(“red”, “Green”, array(12,34), “kamper”);
// you sent me the following arguments:
// Aguments 0 : red
// Aguments 1 : Green
// Aguments 2 : ARRAY 0 => 12 1 => 34
// Aguments 3 : kamper

// nums list function
function sum(){
$sum = 0;
$args = func_get_args();
for($x=0; $x<sizeof($args); $x++){
if(is_array($args[$x])){
foreach($args[$x] as $a){
$sum += $a;
}
} else {
$sum += $args[$x];
}
}
return $sum;
}
echo “1 + 10 = ” . sum(1, 10); // 1 + 10 = 11
echo “<br>1 + 2  + 4 + 5 = ” . sum(1,2, array(4,5));
// 1 + 2 + 4 + 5 = 12

// menerima berbagiai nilai dari fungsi
function getUser(){
return array(“Suhemi”, “Lampung”, “Sintetic@ispiracy.net”);
}
list ($nama, $lokasi, $email) = getUser();
echo “nama $nama, asal $lokasi. email $email”;

// manipulasi fungsi input dan output dengan reference
function ganti(&$var){
$var = “HAhaha”; return $var;
}
$rab = “HIhihi”;
echo “Before : ” . $rab; // Hihihi
echo “<br>Ganti : “. ganti($rab); //HAhaha
echo “<br>After : ” . $rab;// HAhaha

// fungsi menganti variabel
function &incNum(){
global $num;
$num++;
return $num;
}
$num = 0;
$retVal =& incNum();
echo  “retVal = $retVal <br>”; //retVal : 1
incNum();
echo “Number is : $retVal”; // Number is : 2

// memanggil fungsi dengan menggunakan penggabungan nama
function testCoba($num){
echo “nilai $num”;
}
$op = “test”;
$funct = $op . “Coba”;
$funct(13); // nilai 13

// deklarasi fungsi didalam fungsi
function func1(){
function func2(){
echo “dari fungsi 2”;
}
echo “fungsi 1”;
}
func1();// harus di panggil dahulu
func2();// baru bisa mengakses function ini
//fungsi 1dari fungsi 2

// membuat fungsi reqursif
function calFactorial($num){
static $product = 1;
if($num > 1){
$product = $product * $num;
$num–;
calFactorial($num);
}
return $product;
}

echo calFactorial(5); // 120

// reqursif untuk membaca direktory
function recDir($dir){
if(!is_dir($dir)) { die(“Bukan direktory”); }
$dh = opendir($dir) or die (“Cannot open dir”);
// iterasi
while (($file = readdir($dh)) !== false) {
if($file != “.” && $file != “..”) {
if(is_dir(“$dir/$file”)){
recDir(“$dir/$file”);
} else {
echo “$dir/$file <br>”;
}
}
}
}
// buat folder pada folder yang sama dengan code
recDir(‘feel’);
//feel/lalala/keahlian.docx
//feel/cv.doc

// mendefinisikan kelas
class Generic {
public $cpu;
public $mem;

public function setMem($val){
$this->mem = $val;
echo “Setting memory ke $val MB”;
}

public function setCpu($val){
$this->cpu = $val;
echo “Setting CPU ke \”$val\”…”;
}

public function getConf() {
echo “Konfigurasi sekarang: $this->cpu CPU , $this->mem MB RAM”;
}
}
$thepc = new Generic;
$thepc->setCpu(“Intel Atom”);
$thepc->setMem(1024);
$thepc->getConf();
//Setting CPU ke “Intel Atom”…Setting memory ke 1024 MBKonfigurasi sekarang: Intel Atom CPU , 1024 MB RAM

// eksekusi otomatis, perintah konstruktor dan desktruktor kelas
class testClass{
function __construct(){//php5
echo “Jalankan konstruktor”;
}
function  __destruct() {
echo “Destruktor  dijalankan”;
}
}
$test = new testClass(); //create
unset($test);// destroy
// Jalankan konstruktorDestruktor dijalankan

// more konstruktor destruktor
class fileLock {
private $file;
public function __construct($file){ //constructor
$this->file = $file;
$this->lock();
}
public function lock() {
clearstatcache(); // clear file cache
//cek, exist ? jika tidak ulangi beberapa detik lagi
echo  “Mencoba mengunci file …<br>”;
if(!file_exists($this->file . ” .lock”)){
touch ($this->file . “.lock”, time()) or
die(“Error : tidak bisa melakukan locking file”);
echo “File locked !”;
} else {
echo “file locking exist,mencoba lagi dalam 2 detik .. <br>”;
sleep(2);
$this->lock();
}
}
public function write($data){
echo “mencoba menulis file”;
if(!$fp = fopen($this->file, “a+”)) {
echo “Error:tidak dapat membuka file”;
return false;
}
if (!fwrite($fp, $data)) {
echo “Error:tidak dapat menulis ke file”;
return false;
}
if(!fclose($fp)) {
echo “Error: cannot closefile!”;
}
echo “Data ditulis ke file !<br>”;
}
public function __destruct() {
$this->unlock();
}
public function unlock(){//metode for unlock
echo “Unlocking file …<br>”;
unlink($this->file . “.lock”) or
die(“Error:tidak bisa menmbuang lock file”);
echo “File unlocked”;
}
}
$f1 = new fileLock(“feel/obj.txt”);
$f1->write(“test penulisan”);
unset($f1);
// coba sendiri di file

// pewarisan
class Generic {
public $cpu;
public $mem;

public function __construct(){
echo “inisialisasi sistem …<br>”;
}
public function setMem($val){
$this->mem = $val;
echo “Setting memory ke $val MB … <br>”;
}
public function setCpu($val){
$this->cpu = $val;
echo “Setting CPU ke \”$val\”…<br>”;
}
public function getConf() {
echo “Konfigurasi sekarang: $this->cpu CPU , $this->mem MB RAM<br>”;
}
}
class Server extends Generic { // new
protected $disk;
function __construct(){
parent::__construct();// jalankan konstructor parent
}
function setDisk($val){// set disk drive spek
$this->disk = $val;
echo “Setting disk storage ke $val GB<br>”;
}
function addMem($val){ // tambah memory
$this->mem += $val;
echo “menambahkan $val MB memory<br>”;
}
public function getConfig(){
echo “Konfigurasi: CPU ” . $this->cpu .
” , $this->mem MB RAM, ” . $this->disk .
” GB disk storage<br>”;
}
}
$webServer = new Server; // create obj
$webServer->setMem(2048);
$webServer->setCpu(“Intel Double Quartet CORE”);
$webServer->setDisk(1024);
// fungsi pada kelas turunan
$webServer->addMem(2048);
// daptkan data
$webServer->getConfig();

// melakukan pengecekan jika fungsi dan kelas
// telah didefiniskan
class aClass{
public function __construct(){
return false;
}
}
echo class_exists(“aClass”)?”Ada” : “tidak”;//ada
echo class_exists(“bClass”)?”Ada” : “tidak”;//tidak

// mengecek keberadaan fungsi didalam kelas
class Dog{
function bark(){
echo “guk.. guk..”;
}
}
echo is_callable(array(“Dog”, “bark”))? “method exists”:”not”;
//method exists

// mengecek keberadaan fungsi dalam kelas (2)
class Cat{
function canBark(){
return method_exists($this, “bark”);
}
}
$tom = new Cat;
echo $tom->canBark() ? “Kucing bisa menggongong”:”tidak bisa”;
// tidak bisa -> perhatikan algoritmanya, berguna untuk kelas turunan

// menerima informasi dari kelas member
class Dog{
public $name;
public $age;

public function __construct(){
echo “construct Dog class<br>”;
}
public function wagTail(){
echo “Happy dog<br>”;
}
}
//extends class
class Bloodhounds extends Dog {
public $color;
public function sniff(){
echo “this dog can smell food a mile away<br>”;
}
public function __destruct(){
echo “destroying a Dog<br>”;
}
}
// create instance
$myDog = new Bloodhounds();
$myDog->name = “Jim”;
$myDog->age = “3”;
$myDog->color = “White”;
// retrieve class name form instance
echo “Class: ” . get_class($myDog) . “<br>”;
// retreive parent class name dari instance
echo “Parent class: ” . get_parent_class(get_class($myDog)) . “<br>”;
//get and print list dari properties class
$vars = get_class_vars(get_class($myDog));
echo “Class Properties: “;
foreach ($vars as $key=>$value){
if(!isset($value)){ $value = “<undef>”;}
echo “$key=$value “;
}
echo “<br>”;
// get and print list of object methods
$methods = get_class_methods(get_class($myDog));
echo “Class method: “;
foreach($methods as $m){
echo “$m “;
}
echo “<br>”;
// dapatkan dan tampilkan list dari instance properties
$vars = get_object_vars($myDog);
echo “Instance properties: “;
foreach($vars as $keys=>$value){
if(!isset($value)) { $value=”<undef>”;}
echo “$key = $value “;
}
echo “<br>”;
/*
construct Dog class
Class: Bloodhounds
Parent class: Dog
Class Properties: color= name= age=
Class method: sniff __destruct __construct wagTail
Instance properties: age = White age = Jim age = 3
destroying a Dog
*/

// menampilkan data pada class
class Dog{
public $breed;
public $name;
public $age;
public function __construct(){
echo “construct the dog..<br>”;
}
}
$newDog = new Dog;
$newDog->breed = “Serigala”;
$newDog->name = “Whitefang”;
$newDog->age = 2;
foreach($newDog as $key=>$value){
echo “$key: $value<br>”;
}
/*construct the dog..
breed: Serigala
name: Whitefang
age: 2*/

// meload class dan fungsi yang dibutuhkan secara otomatis
function __autoload($class){
require “defs/”.$class.”.php”;
}
$obj = new FormHandler();

// mencari persamaan dari objek
class Session {
public $id;
function __construct($id){
$this->id = $id;
}
}
$ca = new Session(100);
$cb = new Session(200);
$cc = new Session(100);
$cd =& $ca;
echo ($ca==$cb)? “true” : “false”; // false
echo ($ca==$cc)? “true” : “false”; // true
echo ($ca===$cd)? “true” : “false”; // true

// menduplikasi kelas
class Dog{
public $name;
public $age;
public function getinfo(){
echo “Nama: $this->name | Umur: $this->age<br>”;
}
}
$d1 = new Dog;
$d1->name = “dodol”;
$d1->age = “3”;
$d1->getinfo();//Nama: dodol | Umur: 3
$d2 = clone $d1;
$d2->name = “wow”;
$d2->getinfo();//Nama: wow | Umur: 3

// membuat properties kelas yang tidak merestrat inisialisasi
class Instance {
static $insCounter = 0;
public function __construct(){
echo “Create new instance …<br>”;
self::$insCounter++;
}
public function getInstanceCounter(){
return self::$insCounter;
}
}
$a = new Instance;
$b = new Instance;
echo “func inscounter “.$a->getInstanceCounter(); //2
echo “var inscounter “.$a->insCounter; // (nothing?)

// memfilter akses kelas turunan

class testCls{
public $publicVar;
private $privateVar;
protected $protectedVar;

public function publicMethod(){return;}
private function privateMethod(){return;}
protected function protectedMethod(return;}
}
$d = new testCls;
$d->publicVar = 5; // work
$d->privateVar = false // error
$d->protectedVar = “dudu”; //error
$d->publicMethod();//work
$d->privateMethod();//error
$d->protectedMethod();//error

// agar kelas tidak dapat diturunkan
final class Generic{
public function __construct(){
echo “inisializing..”;
}
}
class Server extends Generic{ // fatal error
public function __construct(){
parent::__construct();
}
}

// mendefiniskan kelas abstract
abstract class addMachine{
abstract public function add();
abstract public function sub();
}
class Kalkulator extends addMachine{
public function __construct($a, $b){
$this->a = $a;
$this->b = $b;
}
}

// overload metode class-> agar memiliki jumlah inputan yg beragam
class KoordinatXY{
public $data;
public function __construct($x, $y){
$this->data = array($x, $y);
}
}
class Render{
public function __call($method, $args){//method overloaded
if($method == “render”){
$numArgs = count($args);
if($numArgs == 1){
echo “Render titik..<br>”;
}
else if($numArgs == 2){
echo “Render garils..<br>”;
}
else if($numArgs >= 3){
echo “Render polygon ..<br>”;
} else
die(“Error: data input salah !!!”);

} else {
die (“Errror: $method tidak dikenal”);
}
}
}

$r = new Render();
// 1 argument
$r->render(new KoordinatXY(1,2)); // render titik
// 2 argument
$r->render(new KoordinatXY(1,2), new KoordinatXY(20, 6));
// 4 argument
$r->render(new KoordinatXY(1,2), new KoordinatXY(20,6), new KoordinatXY(4,4), new KoordinatXY(18,4));

// overload ke dua
class overloadReverse{
public static function __call($method, $args){
if($method == “reverse”) {
//check number of argument
if(sizeof($args) == 1){
$arg = $args[0];
if(is_string($arg)){
return strrev($arg);
} else if(is_numeric($arg)){
return 1/$arg;
} else if(is_array($arg)){
return array_reverse($arg);
} else if(is_bool($arg)){
return ($arg==FALSE)?false:true;
} else if(is_null($arg)){
return null;
}
} else {
die(“ERROR: Input yang tidak benar”);
}
} else {
die(“ERROR: Metode $method tidak dikenal”);
}
}
}

$o = new overloadReverse();
echo $o->reverse(“telur”).”<br>”;
echo $o->reverse().”<br>”;
echo $o->reverse(2).”<br>”;
echo $o->reverse(‘k’, ‘o’, ‘l’, ‘o’, ‘r’).”<br>”;

// membuat “catch-all” class methods
// __call() berguna untuk menangkap semua fungsi yang tidak ada
class virtualMethodClass{
function __call($method, $args){
echo “U called method [$method] with arguments[“.implode(“, “, $args).”]<br>”;
}
}
$obj =  new virtualMethodClass;
$obj->jump(“10”, “inchi”);

<?php
// mendefinisikan fungsi
function getLuasLingkaran($r){
return pi() * $r * $r;
}
echo “luas lingkaran berjari2 10: ” . getLuasLingkaran(10);
//luas lingkaran berjari2 10: 314.15926535898

// menghindari duplikasi fungsi
function asalAja(){
return “exits here”;
}
echo function_exists(“asalAja”)? “Exist” : “Not”; // Exist
echo “<br>” . (function_exists(“tidakAja”)?”ada” : “tidak”); // tidak

// mengakses variabel external dari fungsi
$name = “G3n1k”;
function yes(){
global $name;
return $name;
}
echo yes(); // G3n1k

function yup(){
return $GLOBALS[‘name’];
}
echo yup(); // G3n1k

function yep(){
global $name;
echo “Nama awal: ” . $name . “<br/>”;
$name = ” Curly”;
echo “Nama akhir : ” . $name . “<br/>”;
}
echo “Sebelum fungsi: ” . $name . “<br/>”;
yep();
echo “Sesudah fungsi ” . $name . “<br/>”;
// Sebelum fungsi: G3n1k
// Nama awal: G3n1k
// Nama akhir : Curly
// Sesudah fungsi Curly

// nilai default untuk fungsi
function luas0($r, $pi=3.14″){
return $pi * $r * $r;
}
echo luas0(10). ” fungsi tanpa masukan pi<br>”;
echo luas0(10, pi()) . ” fungsi dengan PI”;
// 314 fungsi tanpa masukan pi
// 314.15926535898fungsi dengan PI

// memproses panjang-variabel daftar Argument
function someFunc() {
$numArgs = func_num_args(); // get argument passed
$args = func_get_args(); // dapatkan argument
print “you sent me the following arguments: “;
for($x = 0; $x<sizeof($args); $x++){
print “<br> Aguments $x :” ;
if(is_array($args[$x])) {
print ” ARRAY “;
foreach ($args[$x] as $index=>$element) {
print ” $index => $element “;
}
} else {
print ” $args[$x] “;
}
}
}
someFunc(“red”, “Green”, array(12,34), “kamper”);
// you sent me the following arguments:
// Aguments 0 : red
// Aguments 1 : Green
// Aguments 2 : ARRAY 0 => 12 1 => 34
// Aguments 3 : kamper

// nums list function
function sum(){
$sum = 0;
$args = func_get_args();
for($x=0; $x<sizeof($args); $x++){
if(is_array($args[$x])){
foreach($args[$x] as $a){
$sum += $a;
}
} else {
$sum += $args[$x];
}
}
return $sum;
}
echo “1 + 10 = ” . sum(1, 10); // 1 + 10 = 11
echo “<br>1 + 2  + 4 + 5 = ” . sum(1,2, array(4,5));
// 1 + 2 + 4 + 5 = 12

// menerima berbagiai nilai dari fungsi
function getUser(){
return array(“Suhemi”, “Lampung”, “Sintetic@ispiracy.net”);
}
list ($nama, $lokasi, $email) = getUser();
echo “nama $nama, asal $lokasi. email $email”;

// manipulasi fungsi input dan output dengan reference
function ganti(&$var){
$var = “HAhaha”; return $var;
}
$rab = “HIhihi”;
echo “Before : ” . $rab; // Hihihi
echo “<br>Ganti : “. ganti($rab); //HAhaha
echo “<br>After : ” . $rab;// HAhaha

// fungsi menganti variabel
function &incNum(){
global $num;
$num++;
return $num;
}
$num = 0;
$retVal =& incNum();
echo  “retVal = $retVal <br>”; //retVal : 1
incNum();
echo “Number is : $retVal”; // Number is : 2

// memanggil fungsi dengan menggunakan penggabungan nama
function testCoba($num){
echo “nilai $num”;
}
$op = “test”;
$funct = $op . “Coba”;
$funct(13); // nilai 13

// deklarasi fungsi didalam fungsi
function func1(){
function func2(){
echo “dari fungsi 2”;
}
echo “fungsi 1”;
}
func1();// harus di panggil dahulu
func2();// baru bisa mengakses function ini
//fungsi 1dari fungsi 2

// membuat fungsi reqursif
function calFactorial($num){
static $product = 1;
if($num > 1){
$product = $product * $num;
$num–;
calFactorial($num);
}
return $product;
}

echo calFactorial(5); // 120

// reqursif untuk membaca direktory
function recDir($dir){
if(!is_dir($dir)) { die(“Bukan direktory”); }
$dh = opendir($dir) or die (“Cannot open dir”);
// iterasi
while (($file = readdir($dh)) !== false) {
if($file != “.” && $file != “..”) {
if(is_dir(“$dir/$file”)){
recDir(“$dir/$file”);
} else {
echo “$dir/$file <br>”;
}
}
}
}
// buat folder pada folder yang sama dengan code
recDir(‘feel’);
//feel/lalala/keahlian.docx
//feel/cv.doc

// mendefinisikan kelas
class Generic {
public $cpu;
public $mem;

public function setMem($val){
$this->mem = $val;
echo “Setting memory ke $val MB”;
}

public function setCpu($val){
$this->cpu = $val;
echo “Setting CPU ke \”$val\”…”;
}

public function getConf() {
echo “Konfigurasi sekarang: $this->cpu CPU , $this->mem MB RAM”;
}
}
$thepc = new Generic;
$thepc->setCpu(“Intel Atom”);
$thepc->setMem(1024);
$thepc->getConf();
//Setting CPU ke “Intel Atom”…Setting memory ke 1024 MBKonfigurasi sekarang: Intel Atom CPU , 1024 MB RAM

// eksekusi otomatis, perintah konstruktor dan desktruktor kelas
class testClass{
function __construct(){//php5
echo “Jalankan konstruktor”;
}
function  __destruct() {
echo “Destruktor  dijalankan”;
}
}
$test = new testClass(); //create
unset($test);// destroy
// Jalankan konstruktorDestruktor dijalankan

// more konstruktor destruktor
class fileLock {
private $file;
public function __construct($file){ //constructor
$this->file = $file;
$this->lock();
}
public function lock() {
clearstatcache(); // clear file cache
//cek, exist ? jika tidak ulangi beberapa detik lagi
echo  “Mencoba mengunci file …<br>”;
if(!file_exists($this->file . ” .lock”)){
touch ($this->file . “.lock”, time()) or
die(“Error : tidak bisa melakukan locking file”);
echo “File locked !”;
} else {
echo “file locking exist,mencoba lagi dalam 2 detik .. <br>”;
sleep(2);
$this->lock();
}
}
public function write($data){
echo “mencoba menulis file”;
if(!$fp = fopen($this->file, “a+”)) {
echo “Error:tidak dapat membuka file”;
return false;
}
if (!fwrite($fp, $data)) {
echo “Error:tidak dapat menulis ke file”;
return false;
}
if(!fclose($fp)) {
echo “Error: cannot closefile!”;
}
echo “Data ditulis ke file !<br>”;
}
public function __destruct() {
$this->unlock();
}
public function unlock(){//metode for unlock
echo “Unlocking file …<br>”;
unlink($this->file . “.lock”) or
die(“Error:tidak bisa menmbuang lock file”);
echo “File unlocked”;
}
}
$f1 = new fileLock(“feel/obj.txt”);
$f1->write(“test penulisan”);
unset($f1);
// coba sendiri di file

// pewarisan
class Generic {
public $cpu;
public $mem;

public function __construct(){
echo “inisialisasi sistem …<br>”;
}
public function setMem($val){
$this->mem = $val;
echo “Setting memory ke $val MB … <br>”;
}
public function setCpu($val){
$this->cpu = $val;
echo “Setting CPU ke \”$val\”…<br>”;
}
public function getConf() {
echo “Konfigurasi sekarang: $this->cpu CPU , $this->mem MB RAM<br>”;
}
}
class Server extends Generic { // new
protected $disk;
function __construct(){
parent::__construct();// jalankan konstructor parent
}
function setDisk($val){// set disk drive spek
$this->disk = $val;
echo “Setting disk storage ke $val GB<br>”;
}
function addMem($val){ // tambah memory
$this->mem += $val;
echo “menambahkan $val MB memory<br>”;
}
public function getConfig(){
echo “Konfigurasi: CPU ” . $this->cpu .
” , $this->mem MB RAM, ” . $this->disk .
” GB disk storage<br>”;
}
}
$webServer = new Server; // create obj
$webServer->setMem(2048);
$webServer->setCpu(“Intel Double Quartet CORE”);
$webServer->setDisk(1024);
// fungsi pada kelas turunan
$webServer->addMem(2048);
// daptkan data
$webServer->getConfig();

// melakukan pengecekan jika fungsi dan kelas
// telah didegfiniskan
class aClass{
public function __construct(){
return false;
}
}
echo class_exists(“aClass”)?”Ada” : “tidak”;//ada
echo class_exists(“bClass”)?”Ada” : “tidak”;//tidak

// mengecek keberadaan fungsi didalam kelas
class Dog{
function bark(){
echo “guk.. guk..”;
}
}
echo is_callable(array(“Dog”, “bark”))? “method exists”:”not”;
//method exists

// mengecek keberadaan fungsi dalam kelas (2)
class Cat{
function canBark(){
return method_exists($this, “bark”);
}
}
$tom = new Cat;
echo $tom->canBark() ? “Kucing bisa menggongong”:”tidak bisa”;
// tidak bisa -> perhatikan algoritmanya, berguna untuk kelas turunan

// menerima informasi dari kelas member
class Dog{
public $name;
public $age;

public function __construct(){
echo “construct Dog class<br>”;
}
public function wagTail(){
echo “Happy dog<br>”;
}
}
//extends class
class Bloodhounds extends Dog {
public $color;
public function sniff(){
echo “this dog can smell food a mile away<br>”;
}
public function __destruct(){
echo “destroying a Dog<br>”;
}
}
// create instance
$myDog = new Bloodhounds();
$myDog->name = “Jim”;
$myDog->age = “3”;
$myDog->color = “White”;
// retrieve class name form instance
echo “Class: ” . get_class($myDog) . “<br>”;
// retreive parent class name dari instance
echo “Parent class: ” . get_parent_class(get_class($myDog)) . “<br>”;
//get and print list dari properties class
$vars = get_class_vars(get_class($myDog));
echo “Class Properties: “;
foreach ($vars as $key=>$value){
if(!isset($value)){ $value = “<undef>”;}
echo “$key=$value “;
}
echo “<br>”;
// get and print list of object methods
$methods = get_class_methods(get_class($myDog));
echo “Class method: “;
foreach($methods as $m){
echo “$m “;
}
echo “<br>”;
// dapatkan dan tampilkan list dari instance properties
$vars = get_object_vars($myDog);
echo “Instance properties: “;
foreach($vars as $keys=>$value){
if(!isset($value)) { $value=”<undef>”;}
echo “$key = $value “;
}
echo “<br>”;
/*
construct Dog class
Class: Bloodhounds
Parent class: Dog
Class Properties: color= name= age=
Class method: sniff __destruct __construct wagTail
Instance properties: age = White age = Jim age = 3
destroying a Dog
*/

// menampilkan data pada class
class Dog{
public $breed;
public $name;
public $age;
public function __construct(){
echo “construct the dog..<br>”;
}
}
$newDog = new Dog;
$newDog->breed = “Serigala”;
$newDog->name = “Whitefang”;
$newDog->age = 2;
foreach($newDog as $key=>$value){
echo “$key: $value<br>”;
}
/*construct the dog..
breed: Serigala
name: Whitefang
age: 2*/

// meload class dan fungsi yang dibutuhkan secara otomatis
function __autoload($class){
require “defs/”.$class.”.php”;
}
$obj = new FormHandler();

// mencari persamaan dari objek
class Session {
public $id;
function __construct($id){
$this->id = $id;
}
}
$ca = new Session(100);
$cb = new Session(200);
$cc = new Session(100);
$cd =& $ca;
echo ($ca==$cb)? “true” : “false”; // false
echo ($ca==$cc)? “true” : “false”; // true
echo ($ca===$cd)? “true” : “false”; // true

// menduplikasi kelas
class Dog{
public $name;
public $age;
public function getinfo(){
echo “Nama: $this->name | Umur: $this->age<br>”;
}
}
$d1 = new Dog;
$d1->name = “dodol”;
$d1->age = “3”;
$d1->getinfo();//Nama: dodol | Umur: 3
$d2 = clone $d1;
$d2->name = “wow”;
$d2->getinfo();//Nama: wow | Umur: 3

// mempbuat properties kelas yang tidak merestrat inisialisasi
class Instance {
static $insCounter = 0;
public function __construct(){
echo “Create new instance …<br>”;
self::$insCounter++;
}
public function getInstanceCounter(){
return self::$insCounter;
}
}
$a = new Instance;
$b = new Instance;
echo “func inscounter “.$a->getInstanceCounter(); //2
echo “var inscounter “.$a->insCounter; // (nothing?)

// memfilter akses kelas turunan
class testCls{
public $publicVar;
private $privateVar;
protected $protectedVar;

public function publicMethod(){return;}
private function privateMethod(){return;}
protected function protectedMethod(return;}
}
$d = new testCls;
$d->publicVar = 5; // work
$d->privateVar = false // error
$d->protectedVar = “dudu”; //error
$d->publicMethod();//work
$d->privateMethod();//error
$d->protectedMethod();//error

// agar kelas tidak dapat diturunkan
final class Generic{
public function __construct(){
echo “inisializing..”;
}
}
class Server extends Generic{ // fatal error
public function __construct(){
parent::__construct();
}
}

// mendefiniskan kelas abstract
abstract class addMachine{
abstract public function add();
abstract public function sub();
}
class Kalkulator extends addMachine{
public function __construct($a, $b){
$this->a = $a;
$this->b = $b;
}
}

// overload metode class-> agar memiliki jumlah inputan yg beragam
class KoordinatXY{
public $data;
public function __construct($x, $y){
$this->data = array($x, $y);
}
}
class Render{
public function __call($method, $args){//method overloaded
if($method == “render”){
$numArgs = count($args);
if($numArgs == 1){
echo “Render titik..<br>”;
}
else if($numArgs == 2){
echo “Render garils..<br>”;
}
else if($numArgs >= 3){
echo “Render polygon ..<br>”;
} else
die(“Error: data input salah !!!”);

} else {
die (“Errror: $method tidak dikenal”);
}
}
}

$r = new Render();
// 1 argument
$r->render(new KoordinatXY(1,2)); // render titik
// 2 argument
$r->render(new KoordinatXY(1,2), new KoordinatXY(20, 6));
// 4 argument
$r->render(new KoordinatXY(1,2), new KoordinatXY(20,6), new KoordinatXY(4,4), new KoordinatXY(18,4));

// overload ke dua
class overloadReverse{
public static function __call($method, $args){
if($method == “reverse”) {
//check number of argument
if(sizeof($args) == 1){
$arg = $args[0];
if(is_string($arg)){
return strrev($arg);
} else if(is_numeric($arg)){
return 1/$arg;
} else if(is_array($arg)){
return array_reverse($arg);
} else if(is_bool($arg)){
return ($arg==FALSE)?false:true;
} else if(is_null($arg)){
return null;
}
} else {
die(“ERROR: Input yang tidak benar”);
}
} else {
die(“ERROR: Metode $method tidak dikenal”);
}
}
}

$o = new overloadReverse();
echo $o->reverse(“telur”).”<br>”;
echo $o->reverse().”<br>”;
echo $o->reverse(2).”<br>”;
echo $o->reverse(‘k’, ‘o’, ‘l’, ‘o’, ‘r’).”<br>”;

// membuat “catch-all” class methods
// __call() berguna untuk menangkap semua fungsi yang tidak ada
class virtualMethodClass{
function __call($method, $args){
echo “U called method [$method] with arguments[“.implode(“, “, $args).”]<br>”;
}
}
$obj =  new virtualMethodClass;
$obj->jump(“10”, “inchi”);
?>

Published by

G3n1k

just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s