Tizag.com Webmaster Tutorials - A collection of webmaster tutorials from HTML to PHP.

Monday, January 25, 2010

Calling Methods of PHP Class Globally

<?php
class saveData{
private $filelocation, $dataSaved;

public function __construct($file, $data){
$this->filelocation = $file;
$this->dataSaved = $data;

if(!$data || strlen($data)>=256){
throw new Exception("Text shold not be more than 256 characters.");
}
if(!file_exists($file)){
throw new Exception("File missing in the location specified.");
}
}


public function saveData(){
if(!$fp = fopen($this->filelocation, 'a+')){
throw new Exception("Error in opeining the target file.");
}
if(!fwrite($fp, $this->dataSaved)){
throw new Exception("Error in writing in the target file.");
}
fclose($fp);
}

public function __toString(){
return "Data Successfully Saved.";
}
}
?>

<html>
<head>
<title>Save Data | Calling Methods of a Class Globally</title>
</head>
<body>
<form name="frm1">
<textarea name="typeValue" cols="20" rows="8"/></textarea>
<input type ="submit"/>
</form>
<?php
if($_REQUEST){
if($_REQUEST["typeValue"]){
try{
$dataSaver = new saveData("document.txt", $_REQUEST["typeValue"] );
$dataSaver->saveData();
echo $dataSaver;
}
//catch exception
catch(Exception $e){
echo 'Message: ' .$e->getMessage();
}


}
}
?>
</body>
</html>

No comments: