Monday, June 16, 2008

PHP: Code Snippets ..

/** 1. returns count of the processes currently running
* Input : name of the process like garbageCollector
* Output : count of the processes running.
*
Use eg.: echo checkProcess("java");
*/
function checkProcess($processName = "garbageCollector") {
return $processCount = shell_exec("ps ax | grep $processName | grep -v grep | wc -l");
}

/** 2. returns name of the tables which suffix is in Date format Ymd
* Input : table count, table name, suffix date format
* Output : count of the processes running.
* Use eg. : echo findNames(10, "TABLE");
*/
function findNames($countTables, $str, $format = "Ymd") {
$retStr = "";
for($i = 0; $i < $countTables; $i++) $retStr .= $str.date($format, mktime(0, 0, 0, 01, 01 + $i, 2008)).","; return $retStr = substr($retStr, 0, strlen($retStr) - 1); }


/*** 4. ***/

for($i = -19; $i < 0; $i++) {
echo $date = date("Y-m-d", strtotime("$i day"));
}

/*** 3. **
* Polymorphism Example
*/

class Car{

 private $name;
function __construct($n) {
$this->set_name($n);
}
function set_name($n) {
$this->name = $n;
}
function get_name() {
return $this->name;
}
function accelerate() {
echo "Now I'm running 10 mile faster\n";
}
}

class SportsCar extends Car
{
function __construct($n) {
parent::__construct($n);
}
function accelerate() {
echo "Now I'm running 20 mile faster\n";
}
}

// an array of cars of different types
$cars = array(new Car("Ford"), new SportsCar("Porche"));
foreach ($cars as $c) {
$c->accelerate(); // polymorphic behaviors
}

No comments: