unexpected T_TRY, expecting T_FUNCTION error message, not sure why? - php

I am getting unexpected T_TRY, expecting T_FUNCTION error message and am not sure as too why am getting that, can't we use try and catch block inside class like this:
class Processor
{
protected $dao;
protected $fin;
try
{
public function __construct($file)
{
//Open File for parsing.
$this->fin = fopen($file,'w+') or die('Cannot open file');
// Initialize the Repository DAO.
$this->dao = new Dao('some name');
}
public function initiateInserts()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_inserts = $this->dao->initiateInserts($data);
}
}
public function initiateCUpdates()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_updates = $this->dao->initiateCUpdates($data);
}
}
public function initiateExecuteIUpdates()
{
while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
{
$initiate_updates = $this->dao->initiateIUpdates($data);
}
}
}
catch (Exception $e)
{
}
}

You can't put all your method definitions into one try-catch block.
Instead of
class Foo {
try {
public function func1() { }
public function func2() { }
}
catch(Exception $e) {
}
}
you have to use
class Foo {
public function func1() {
try {
...
}
catch(Exception $e) {
...
}
}
public function func2() {
try {
...
}
catch(Exception $e) {
...
}
}
}

Don't try-catch inside of each method, you could simply try-catch when you use your class:
try {
$p = new Processor($file);
$p->initiateInserts();
$p->initiateCUpdates();
// and so on...
} catch (Exception $e) {
// handle the error...
}
This way your class will be much cleaner and you can decide what to do with errors. Especially if you use your class in multiple places - you can have customized error handling for each case.

You can't have any "do this stuff"-code in a class outside of a method. There is nothing to "try to do" inside those curly brackets, because the stuff inside is just method definitions.

Related

Why is my exception thrown from a closure not caught?

I've written a PHPUnit test that checks if an exception is thrown from a closure when a method is invoked. The closure function is passed in as an argument to the method with an exception being thrown from it.
public function testExceptionThrownFromClosure()
{
try {
$this->_externalResourceTemplate->get(
$this->_expectedUrl,
$this->_paramsOne,
function ($anything) {
throw new Some_Exception('message');
}
);
$this->fail("Expected exception has not been found");
} catch (Some_Exception $e) {
var_dump($e->getMessage()); die;
}
}
The code for the get function specified on the ExternalResourceTemplate is
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
}
}
Any ideas why the fail assert statement is called? Can you not catch exceptions thrown from closures in PHP or is there a specific way of dealing with them I don't know about.
For me the exception should just propagate out the return stack, but it doesn't appear to. Is this a bug? FYI I'm running PHP 5.3.3
Thanks for the answers...
Managed to figure out the issue. It looks like the problem is that the try-catch block that's being invoked is the one where the closure is invoked. Which makes sense...
So the code above should be
public function get($url, $params, $closure)
{
try {
$this->_getHttpClient()->setUri($url);
foreach ($params as $key => $value) {
$this->_getHttpClient()->setParameterGet($key, $value);
}
$response = $this->_getHttpClient()->request();
return $closure($response->getBody());
} catch (Exception $e) {
//Log
//Monitor
throw new Some_Specific_Exception("Exception is actually caught here");
}
}
So it looks like PHP 5.3.3 doesn't have a bug after all which was mentioned. My mistake.
I cannot reproduce the behavior, my example script
<?php
class Some_Exception extends Exception { }
echo 'php ', phpversion(), "\n";
$foo = new Foo;
$foo->testExceptionThrownFromClosure();
class Foo {
public function __construct() {
$this->_externalResourceTemplate = new Bar();
$this->_expectedUrl = '_expectedUrl';
$this->_paramsOne = '_paramsOne';
}
public function testExceptionThrownFromClosure()
{
try {
$this->_externalResourceTemplate->get(
$this->_expectedUrl,
$this->_paramsOne,
function ($anything) {
throw new Some_Exception('message');
}
);
$this->fail("Expected exception has not been found");
} catch (Some_Exception $e) {
var_dump('my exception handler', $e->getMessage()); die;
}
}
}
class Bar {
public function get($url, $p, $fn) {
$fn(1);
}
}
prints
php 5.4.7
string(20) "my exception handler"
string(7) "message"
as expected

php manual exception example

So I was reading the php manual on Extending Exceptions and read the example code. My question about the following code is: why does var_dump($o) evaluate to null? Is it because the constructor of the class TestException throws an exception, hence not allowing the completion of the object? I am almost certain that is the reason.
Nevertheless here is the code for examination:
<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0, Exception $previous = null) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code, $previous);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
/**
* Create a class to test the exception
*/
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 is not allowed as a parameter', 6);
break;
default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}
// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
?>
Have a look at PHP exception from PHP official site.
Example:
<?php
class MyException extends Exception { }
class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
/* rethrow it */
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>

Exception handling in php

I have this scenario:
Interface ClassInterface
{
public function getContext();
}
Class A implements ClassInterface
{
public function getContext()
{
return 'CONTEXTA';
}
//Called in controller class
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class B implements ClassInterface
{
public function getContext()
{
return 'CONTEXTB';
}
//Called in controller class
public function Bmethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class Helper {
public function helperMethod(ClassInterface $interface)
{
try {
$this->verifyContext($interface->getContext());
//dosomething
} catch(\Exception $ex) {
throw $ex;
}
}
private function verifyContext($context) {
if (condition1) {
throw new \UnexpectedValueException('Invalid context.');
}
return true;
}
}
I want my controller class which calls Amethod1 and Bmethod1 to know the type of exception(s) thrown in the process. Is it advisable to rethrow an exception just like it was presented?
Do you think the throw-catch-throw-catch-throw structure reasonable in this case?
Yes, totally reasonable. But: your specific example can be simplified from:
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
To:
public function Amethod1()
{
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
}

how do I stop further methods in a PHP class?

I am learning OOP with PHP. I am creating a class to extract XML data from a website. My question is how do I stop the given object from executing more methods if there is an error with the first method. For example, I want to send the URL:
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
echo "Missing URL";
}
}
public function secondJob()
{
whatever
}
}
when I write like this:
$map = new GEOCACHE ("");
$map->secondJob("name");
How do I prevent the secondJob method from being executed in that given object without the script terminating?
Throw an Exception in the constructor, therefore the object will never be created
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("URL is Empty");
}
}
You can then do something like this:
try
{
$map = new GEOCACHE ("");
$map->secondJob("name");
}
catch ( Exception $e)
{
die($e->getMessage());
}
Consider using exceptions in order to control the flow of the script. Throw an exception in the constructor, and catch it outside.
class GEOCACHE {
public $url;
public function __construct($url)
{
$this->url=$url;
if (empty($this->url))
{
throw new Exception("Missing URL");
}
}
public function secondJob()
{
whatever
}
}
try{
$map = new GEOCACHE ("");
$map->secondJob("name");
}catch($e){
// handle error.
}
Throw an exception from __construct
public function __construct($url)
{
if(null == $url || $url == '')
{
throw new Exception('Your Message');
{
}
then in your code
try
{
$geocache = new Geocache($url);
$geocache->secondJob();
// other stuff
}
catch (exception $e)
{
// logic to perform if the geocode object fails
}

Break method chaining in php

I am using method chaining for my class structure.
So my problem is that , how could i break my chain when error occurred in some function.
Below is my code:
<?php
class demo
{
public __construct()
{
$this->a='a';
$this->b='b';
$this->error = false;
}
public function demo1()
{
// Some operation here
// Now based on that operation
if(Operation success)
{
return $this;
}
else
{
// What should i write here which break the chain of methods.
// It will not execute the second function demo2
}
}
public function demo2()
{
// Some operation here
// After function Demo1
}
}
$demoClass = new demo();
$demoClass->demo1()->demo2();
?>
EDIT:
$demoClass = new demo();
try
{
$demoClass->demo1()->demo2();
}
catch(Exception $e)
{
echo "Caught Exception:->".$e->getMessage();
}
Thanks
Avinash
I think you need to throw user exception there.
if(Operation success)
{
return $this;
}
else
{
// What should i write here which break the chain of methods.
// It will not execute the second function demo2
throw new Exception('error');
}

Categories