php 构造函数参数

发布时间:2021-07-24 14:22:35 阅读:1096次

https://blog.csdn.net/besily/article/details/5069383

https://www.cnblogs.com/hpliu2729/archive/2013/03/28/2987396.html

https://blog.csdn.net/qq_14989227/article/details/74783322

在PHP里,如果你没有手写构造函数,则php在实例化这个对象的时候,会自动为类成员以及类方法进行初始化,分配内存等工作,但是有些时候不能满足我们的要求,比如我们要在对象实例化的时候传递参数,那么就需要手动编写构造函数了,手写构造函数有两种写法,只是表现形式不同,其实本质一样
class test
{
    function __construct()
    {
     //your code
    }
}
class test
{
    function test()//如果方法名跟类名字一样,将被认为是构造函数
    {
    //your code
    }
}
以上为两种基本形式
传递参数进行实例化的例子,简单的写一个参考

class test
{
    public $test = '';
    function __construct($input = '')
    {
        $this->test = $input;
    }
    function getTest()
    {
        return $this->test;
    }
}
$a = new test('a test');
echo $a->getTest();

//将输出 a test
$b = new test();
echo $b->getTest();

//没有任何输出

  1. <?php  
  2. class demo{  
  3.   
  4.     private $_args;  
  5.   
  6.     public function __construct(){  
  7.         $args_num = func_num_args(); // 获取参数个数  
  8.   
  9.         // 判断参数个数与类型  
  10.         if($args_num==2){  
  11.             $this->_args = array(  
  12.                                 'id' => func_get_arg(0),  
  13.                                 'dname' => func_get_arg(1)  
  14.                             );  
  15.         }elseif($args_num==1 && is_array(func_get_arg(0))){  
  16.             $this->_args = array(  
  17.                                 'device'=>func_get_arg(0)  
  18.                             );  
  19.         }else{  
  20.             exit('func param not match');  
  21.         }      
  22.     }  
  23.   
  24.     public function show(){  
  25.         echo '<pre>';  
  26.         print_r($this->_args);  
  27.         echo '</pre>';  
  28.     }  
  29.   
  30. }  
  31.   
  32. // demo1
  33. $id = 1; 
  34. $dname = 'fdipzone'
  35. $obj = new demo($id$dname); 
  36. $obj->show(); 
  37. // demo2
  38. $device = array('iOS','Android'); 
  39. $obj = new demo($device);  
  40. $obj->show(); 

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:php 构造函数参数 出自老鄢博客 | 欢迎分享