首页 > 编程技术 > php

php中eval()函数操作数组的方法

发布时间:2016-11-25 14:56

在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作


例子,

<?php
$data="array('key1'=>'value1','key2'=>'value2','key3'=>'value3','key4'=>'value4')";
$arr = eval("return $data;");
var_dump($arr);//array

/*
array
  'key1' => string 'value1' (length=6)
  'key2' => string 'value2' (length=6)
  'key3' => string 'value3' (length=6)
  'key4' => string 'value4' (length=6)
*/

网上很多说使用disable_functions禁止掉eval的方法都是错误的!

其实eval()是无法用php.ini中的disable_functions禁止掉的 :

because eval() is a language construct and not a function

eval是zend的,因此不是PHP_FUNCTION 函数;

那么php怎么禁止eval呢?

如果想禁掉eval可以用php的扩展 Suhosin:
安装Suhosin后在php.ini中load进来Suhosin.so,再加上suhosin.executor.disable_eval = on即可

self()是用在类中了这个new self()用法小编第一次听说过了,不过看了一些相关文章 self()与this有那么一像但又不全像,下面我们来看看php中new self()关键字的用法.


php  new self() 一般在类内部使用,作用是对自身类实例化,下面给个实例讲解如何使用:

<?php
class phpernote{
 public function __construct(){
  echo '一聚教程网!';
 }
 public static function getInstance(){
  new self();
 }
}
 
phpernote::getInstance();

返回结果:

一聚教程网!

例子

//self是指向类的本身,只跟类有关,跟任何对象实例无关

class test_self{
    private static $first_count; //定义静态变量
    private $last_count;
    function __construct(){
        $this->last_count=++self::$first_count;//直接用self调用变量的值赋值给另一个变量
    }
    function __destruct(){}
    function print_self(){
        print($this->last_count);
    }
}

$abc=new test_self();//实例化对象
$abc->print_self();//1
echo '<br />';

总结,,self是指向当前类的指针意思就是指类的本身了,所以我们如果要调用自己的话就可以这new self来创建了

异常处理我们很少接触到BADMETHODCALLEXCEPTION类了,那么这个BADMETHODCALLEXCEPTION类如何来使用?具体的步骤一聚教程小伙伴就为各位介绍一下。


BadMethodCallException是PHP标准库里的异常处理类,是PHP自带的,比如在很多框架中可以看见继承BadMethodCallException类,如Yii2中:


namespace yii\base;
 
/**
 * InvalidCallException represents an exception caused by calling a method in a wrong way.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class InvalidCallException extends \BadMethodCallException
{
    /**
     * @return string the user-friendly name of this exception
     */
    public function getName()
    {
        return 'Invalid Call';
    }
}

BadMethodCallException类又是继承BadFunctionCallException的:


 BadMethodCallException extends BadFunctionCallException {
/* 继承的属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 继承的方法 */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

用法,在控制中:


public function actionResetPassword($token)
{
    try {
        $model = new ResetPasswordForm($token);
    } catch (InvalidParamException $e) {
        throw new BadRequestHttpException($e->getMessage());
    }
 
    if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
        Yii::$app->getSession()->setFlash('success', 'New password was saved.');
 
        return $this->goHome();
    }
 
    return $this->render('resetPassword', [
        'model' => $model,
    ]);
}

用于捕获异常。

当然除了上面介绍的还异常处理类Exception


1、首先php5提供了基本的异常处理类,可直接使用
 
<?php
class Exception
{
protected $message = 'Unknown exception'; // 异常信息
protected $code = 0; // 用户自定义异常代码
protected $file; // 发生异常的文件名
protected $line; // 发生异常的代码行号
function __construct($message = null, $code = 0);
final function getMessage(); // 返回异常信息
final function getCode(); // 返回异常代码
final function getFile(); // 返回发生异常的文件名
final function getLine(); // 返回发生异常的代码行号
final function getTrace(); // backtrace() 数组
final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
/* 可重载的方法 */
function __toString(); // 可输出的字符串
}
?>

简单的使用如下:(通过异常,抛出错误信息)
 
try {
$error = 'my error!';
throw new Exception($error)
} catch (Exception $e) {
echo $e->getMessage();
}

2、我们可以扩展此类,方便我们的使用
 
class MyException extends Exception
{
// 重定义构造器使 message 变为必须被指定的属性
public function __construct($message, $code = 0) {
// 自定义的代码
// 确保所有变量都被正确赋值
parent::__construct($message, $code);
}
// 自定义字符串输出的样式
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}

异常处理的基本思想是代码在try代码被调用执行。如果try码块出现错误,我们可以执行一个抛出异常的处理。某些编程语言,如java,,在特定情况下将自动抛出异常。在php中,异常必须手动抛出。可以使用如下方式抛出一个异常:
  Throw new Exception(‘message',code);
  Throw 关键字将触发异常处理机制,它是一个语言结构,而不是一个函数,但是必须给它传递一个值。它要求一个接受对象。在最简单的情况下,可以实例化一个内置的Exception类。
  最后,在try代码之后,必须至少给出一个catch代码块。可以将多个catch代码块与一个try代码块进行关联。如果每个catch代码块可以捕获一个不同类型的异常,可以使用多个catch代码块是有意义的。例如,如果想捕获Exception类的异常,代码如下
 
Catch(Exception $e)
{
//handing exception
}
Catch代码捕获的对象就是导致异常并传递给throw语句的对象(被throw 语句抛出)。使用Exception 类的实例,是不错的选择。
Exception类提供了如下的内置方法:
  Getcode()   —返回传递给构造函数的代码。
  GetMessage() —返回传递给构造函数的消息。
  getFile()     —返回产生异常代码的文件的路径
  getLine()    —返回产生异常的代码所在的行。

注意:
当捕获到一个异常后,try()块里面的后续代码将不会继续执行,而是会尝试查找匹配的“catch”代码块
当抛出一个异常后,如果不进行catch处理,则会报“Uncaught exception 'Exception'”错误
 
<?php
function test($val){
if ($val>100){
throw new Exception("提示信息:您输入的值过大");
}
}
test(111);
?>

3.当一个异常抛出后,catch语句块可以进行处理也可以不处理
以下是我用户注册功能的部分代码
 
try{
//check forms filled in
if(!filled_out($_POST)){
throw new Exception('你还没有填写表单,请回去填写');
}
//check email address not valid
if(!check_email($email)){
throw new Exception('邮件的格式不正确');
}
//检查密度的长度是否大于6
if(strlen($passwd<6)){
throw new Exception('密度的长度应该大于6');
}
//检查两次密码是否相等
if($passwd!=$passwd1){
throw new Exception('两次密码不一样,请重新输入');
}
//检查用户名的长度是否正确
if(strlen($username)>16){
throw new Exception('用户名的长度不符,请重新输入');
}
} catch(Exception $e){
echo $e->getMessage(); //输出异常信息。
}

百度搜索了一下关于PHP5.6新特性发现本站有整理过一篇相关的文章,但仔细对比了一下本文章与它有一些区别,下面我们来看看


PHP5.6起CONST新特性定义类常量可以使用常量标量表达式(Constant scalar expressions),例如:


<?php
 
class MyTimer {
    const SEC_PER_DAY = 60 * 60 * 24;
}
 
?>

define和CONST的区别是define可以用于定义全局常量,而CONST是定义类的常量。


static静态变量与define,CONST的区别是static定义的变量是可以改变的,而后两者不行,并且static静态变量是随类直接在内存中初始化,可以直接用,如$oneclass::hobby.

define可以定义数组吗?例如define(‘A_ARRAY’,array(‘o’=>’ooo’,’x’=>’xxx’)).

在PHP5.6之前是不行的,但是可以通过serialize把数组序列化,如:


# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
 
# use it
$my_fruits = unserialize (FRUITS);

PHP5.6之后可以直接const定义一个数组:

const DEFAULT_ROLES = array('guy', 'development team');

或者:

const DEFAULT_ROLES = ['guy', 'development team'];

如果是PHP7,可以直接用define定义数组:


define('DEFAULT_ROLES', array('guy', 'development team'));

匿名函数是PHP5.3引进来了,php5.3不但引进了匿名函数还有更多更好多新的特性了,下面我们一起来了解一下PHP匿名函数与注意事项详解


PHP5.2 以前:autoload, PDO 和 MySQLi, 类型约束
PHP5.2:JSON 支持
PHP5.3:弃用的功能,匿名函数,新增魔术方法,命名空间,后期静态绑定,Heredoc 和 Nowdoc, const, 三元运算符,Phar
PHP5.4:Short Open Tag, 数组简写形式,Traits, 内置 Web 服务器,细节修改
PHP5.5:yield, list() 用于 foreach, 细节修改
PHP5.6: 常量增强,可变函数参数,命名空间增强


现在基本上都使用PHP5.3以后的版本,但是感觉普遍一个现象就是很多新特性,过了这么长时间,还没有完全普及,在项目中很少用到。

看看PHP匿名函数:

 'test' => function(){
        return 'test'
},

PHP匿名函数的定义很简单,就是给一个变量赋值,只不过这个值是个function。

以上是使用Yii框架配置components文件,加了一个test的配置。

在另一个模板页面打印试试:

 

<?= app-="">test ?>//test
OK.

什么是PHP匿名函数?

看官方解释:

匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

匿名函数示例

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// 输出 helloWorld
?>

闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号:

匿名函数变量赋值示例


<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
 
$greet('World');
$greet('PHP');
?>
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。

从父作用域继承变量

<?php
$message = 'hello'
 
// 没有 "use"
$example = function () {
    var_dump($message);
};
echo $example();
 
// 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();
 
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world'
echo $example();
 
// Reset message
$message = 'hello'
 
// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();
 
// The changed value in the parent scope
// is reflected inside the function call
$message = 'world'
echo $example();
 
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello");
?>

以上例程的输出类似于:


Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"


php中的匿名函数的注意事项

在php5.3以后,php加入匿名函数的使用,今天在使用匿名的时候出现错误,不能想php函数那样声明和使用,详细看代码

$callback=function(){
  return "aa";
};
echo $callback();
 这是打印出来是aa;

看下面的例子:

echo $callback();
$callback=function(){
  return "aa";
};
 这是报错了!报的错误时:

Notice: Undefined variable: callback in D:\php\www\zf2\public\04.php on line 9
Fatal error: Function name must be a string in D:\php\www\zf2\public\04.php on line 9

$callback为未声明,

但是使用php自己声明的函数都不会报错的!

function callback(){
  return "aa";
}
echo callback();  //aa
 
echo callback();  //aa
function callback(){
  return "aa";
}
 这两个都打印出来aa;

在使用匿名函数的时候,匿名函数当做变量,须提前声明,js中也是这样的!!!!!

标签:[!--infotagslink--]

您可能感兴趣的文章: