zoukankan      html  css  js  c++  java
  • php魔术方法

    <?php
    // Declare a simple class
    class TestClass
    {
        public $foo;
    
        public function __construct($foo) 
        {
            $this->foo = $foo;
        }
    
        public function __toString() {
            return $this->foo;
        }
    }
    
    $class = new TestClass('Hello');
    echo $class;   // Hello
    ?>
    class CallableClass 
    {
        function __invoke($x) {
            var_dump($x);
        }
    }
    $obj = new CallableClass;
    $obj(5);//5
    var_dump(is_callable($obj));//is_callable — 检测参数是否为合法的可调用结构  true
    <?php
    class Connection 
    {
        protected $link;
        private $server, $username, $password, $db;
        
        public function __construct($server, $username, $password, $db)
        {
            $this->server = $server;
            $this->username = $username;
            $this->password = $password;
            $this->db = $db;
            $this->connect();
        }
        
        private function connect()
        {
            $this->link = mysql_connect($this->server, $this->username, $this->password);
            mysql_select_db($this->db, $this->link);
        }
        
        public function __sleep()
        {
            return array('server', 'username', 'password', 'db');
        }
        
        public function __wakeup()
        {
            $this->connect();
        }
    }
    ?>
    <?php
    class MethodTest 
    {
        public function __call($name, $arguments) 
        {
            // 注意: $name 的值区分大小写
            echo "Calling object method '$name' "
                 . implode(', ', $arguments). "
    ";
        }
    
        /**  PHP 5.3.0之后版本  */
        public static function __callStatic($name, $arguments) 
        {
            // 注意: $name 的值区分大小写
            echo "Calling static method '$name' "
                 . implode(', ', $arguments). "
    ";
        }
    }
    
    $obj = new MethodTest;
    $obj->runTest('in object context');
    
    MethodTest::runTest('in static context');  // PHP 5.3.0之后版本
    ?>
  • 相关阅读:
    webpack loader和插件的编写原理
    vue和react原理性知识点
    详谈Javascript类与继承
    vue项目中要实现展示markdown文件[转载]
    前端知识总结--2 js部分
    前端知识总结--html
    react相关知识点总结
    优秀文章
    项目部署服务器2
    项目部署服务器
  • 原文地址:https://www.cnblogs.com/isuben/p/5641388.html
Copyright © 2011-2022 走看看