[PHP] Convert 'variables' to 'files that can be imported' and use exceptions_PHP tutorial

WBOY
Release: 2016-07-14 10:06:35
Original
768 people have browsed it

Talk, I recently read a book called "The Way to Concise Code". The book talks about how to make your code easier to read, and I have benefited a lot. Friends who are interested can take a look.

PHPer rarely uses exceptions. Even if you are a big boss in the company, you may not use exceptions. In more cases, exceptions are just treated as another implementation of error code. I remember I mentioned anomalies in my previous blog, but no one seemed to support it.

Imagine: the following situation occurs in a code:


[php]

if(($retCode = fun1()) == 0){
$html = "Hello,world";
If(($retCode = fun2()) == 0){
If(($retCode = fun3()) == 0){
         }else{
                          //Error          } 
}else{
//Something went wrong
}  
}else{
//An error occurred
}

if(($retCode = fun1()) == 0){

$html = "Hello,world";
if(($retCode = fun2()) == 0){
if(($retCode = fun3()) == 0){
}else{
//Something went wrong
}
}else{
//An error occurred
}
}else{
//An error occurred
}

Are you familiar with the above code? When I looked at the source code of discuz before, there was a piece of code with a similar structure. Writing like this is really expensive, especially when people later come to read this code. We really don’t have the habit of refactoring. Using exception refactoring can solve this problem

[php]

try{
fun1();
fun2();
fun3();
}catch(Exception_FUNC_1 $e){
//Error handling
}catch(Exception_FUNC_2 $e){
//Error handling
}catch(Exception_FUNC_3 $e){
//Error handling
}

try{

fun1();
fun2();
fun3();
}catch(Exception_FUNC_1 $e){
//Error handling
}catch(Exception_FUNC_2 $e){
//Error handling
}catch(Exception_FUNC_3 $e){
//Error handling
}

Isn’t it better? Can it be further optimized?

[php]

try{
fun1();
fun2();
fun3();
}catch(Exception $e){
echo $e->getMessage();
}

function fun1(){
Throw new Exception("Your input is empty", 10001);
}

try{

fun1();
fun2();
fun3();
}catch(Exception $e){
echo $e->getMessage();
}
function fun1(){

throw new Exception("Your input is empty", 10001);
}

What are the benefits?

1. You can focus on the normal process without worrying about what will happen if something goes wrong

2. Process the errors in a unified manner and return errors, logs, and tracebacks

3. Add error types at will, because it is customized, you don’t need to maintain a set of error codes

4. The code structure is clear and the maintenance cost is low

5. Unique classes maintain their own exceptions, such as smarty and phpunit. Errors have their own recording methods and are not coupled with the system they are in

Depending on personal habits, I personally highly recommend it

There is such a need:

I want to output a variable (which may be an array, string, or number) to a file, so that this variable can be used after this file is included by other php files, that is:


[php]


$a = array(
0 => 'abc',
1 => array(
'abc' => '2345'
)
);


//The content output to the file is:

{
Return array(
          0 => 'abc',
1 => array(
'abc' => '2345'
)
);
}


$a = array(
0 => 'abc',
1 => array(
'abc' => '2345'
)
);


//The content output to the file is:

{
return array(
0 => 'abc',
1 => array(
'abc' => '2345'
)
);
}

Then, the next file after include is:


[php]
$a = include("file.php");

$a = include("file.php");
It already has this data.

Specifically when it is used, we put the data in the memory into the hard disk. In addition to serializing, this is also a convenient method because there is no need to unserialize. The bad thing is: you can't operate on objects and handles.

This is what I wrote:


[php]

class Code
{
/**
* Convert variables into strings
*
* @param mixed $var Variables containing only strings, numbers, and arrays
* @param string $pfx prefix, the output content is easy to read
*
* @return string
​​*/
Public function var2Str($var, $pfx = ''){
         $str = '';
If(is_array($var)){
               $str = "array(n";
                $pfx .= "t";
foreach($var as $k => $v){
If(is_string($k)){
                       $k = ""{$k}"";
                                                                           $str .= $pfx . "{$k} => " . $this->var2Str($v, $pfx) . ",n";
                                                                                                             $str .= $pfx . ")";
          }elseif(is_int($var) || is_float($var)){
               $str = "{$var}";
          }elseif(is_string($var)){
              $str = ""{$var}"";
                                                                                 return $str;
}  
}

class Code
{
 /**
* Convert variables into strings
*
* @param mixed $var Only variables containing strings, numbers, and arrays
* @param string $pfx prefix, the output content is easy to read
*
* @return string
​*/
    public function var2Str($var, $pfx = ''){
        $str = '';
        if(is_array($var)){
            $str = "array(n";
            $pfx .= "t";
            foreach($var as $k => $v){
                if(is_string($k)){
                    $k = ""{$k}"";
                }      
                $str .= $pfx . "{$k} => " . $this->var2Str($v, $pfx) . ",n";
            }      
            $str .= $pfx . ")";
        }elseif(is_int($var) || is_float($var)){
            $str = "{$var}";
        }elseif(is_string($var)){
            $str = ""{$var}"";
        }      
        return $str;
    }
}

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477914.htmlTechArticle槽吐吐,最近在看一本叫《代码简洁之道》的书,书中讲了如何让自己的代码变得容易读懂,受益匪浅。有兴趣的朋友可以看看。 PHPer很少...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template