📜  PHP静态方法和实例方法的比较

📅  最后修改于: 2022-05-13 02:24:09.419000             🧑  作者: Mango

PHP静态方法和实例方法的比较

静态方法

PHP的静态方法与其他 OOP 语言相同。仅当整个类的特定数据保持不变时才应使用静态方法。例如,假设某个程序员正在制作大学的数据,并且每个对象都需要 getCollegeName函数,该函数为所有对象返回与大学名称相同的大学名称,那么该函数应该是静态的。基本上静态方法用于在没有该类的对象的情况下访问该方法。当有机会在没有类对象帮助的情况下使用方法时,使用静态方法。

例子:


输出:
MNNIT Allahabad

实例方法

当对象不存在而没有机会调用该方法时,使用实例方法。例如,考虑一个 College 类,其中 getPersonName() 方法返回人名。只有当存在特定类型的人员对象时,才应存在此方法。

例子:



 name = $name;
    }
      
    // This function return name
    function getName() {
        return $this -> name;
    }
}
  
// Creating an object of type College
$obj = new College;
  
// Setting name
$obj -> setName("Geeks");
  
// Getting name
echo ($obj -> getName());
?>
输出:
Geeks

实例方法与静态方法的比较:

  • 静态方法可以不带对象调用,而实例方法不可以不带对象调用。
  • 实例方法的执行时间比静态方法快,但在PHP 5.3 版本中存在一个错误,表明静态方法更快,其中引入了后期绑定。

例子:

 count = $this -> count + 2;
    }
}
  
// Creating an instance object
$ob = new Ins;
  
// Starting time is insitialize
$time_start_instance = microtime(true);
  
// For time loop is run
for($i = 0; $i < 100000; $i++)
{
    $ob -> getResult();
}
  
// Execution end for instance method
$time_end_instance = microtime(true);
  
// Total time is end-start time
$time_instance = $time_end_instance - $time_start_instance;
  
// Result is printed
echo "\nTotal execution time for instance method is: '$time_instance'";
?>
输出:
Current PHP version: 7.0.32-0ubuntu0.16.04.1
Total execution time is for static method is: '0.0056149959564209'
Total execution time for instance method is: '0.004885196685791'