How to use testClass method of dateInterval class

Best Atoum code snippet using dateInterval.testClass

scheduled_task_test.php

Source:scheduled_task_test.php Github

copy

Full Screen

1<?php2// This file is part of Moodle - http://moodle.org/3//4// Moodle is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.8//9// Moodle is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.13//14// You should have received a copy of the GNU General Public License15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.16/**17 * This file contains the unittests for scheduled tasks.18 *19 * @package core20 * @category phpunit21 * @copyright 2013 Damyon Wiese22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later23 */24defined('MOODLE_INTERNAL') || die();25require_once(__DIR__ . '/fixtures/task_fixtures.php');26/**27 * Test class for scheduled task.28 *29 * @package core30 * @category task31 * @copyright 2013 Damyon Wiese32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later33 */34class core_scheduled_task_testcase extends advanced_testcase {35 /**36 * Test the cron scheduling method37 */38 public function test_eval_cron_field() {39 $testclass = new \core\task\scheduled_test_task();40 $this->assertEquals(20, count($testclass->eval_cron_field('*/3', 0, 59)));41 $this->assertEquals(31, count($testclass->eval_cron_field('1,*/2', 0, 59)));42 $this->assertEquals(15, count($testclass->eval_cron_field('1-10,5-15', 0, 59)));43 $this->assertEquals(13, count($testclass->eval_cron_field('1-10,5-15/2', 0, 59)));44 $this->assertEquals(3, count($testclass->eval_cron_field('1,2,3,1,2,3', 0, 59)));45 $this->assertEquals(1, count($testclass->eval_cron_field('-1,10,80', 0, 59)));46 }47 public function test_get_next_scheduled_time() {48 global $CFG;49 $this->resetAfterTest();50 $this->setTimezone('Europe/London');51 // Let's specify the hour we are going to use initially for the test.52 // (note that we pick 01:00 that is tricky for Europe/London, because53 // it's exactly the Daylight Saving Time Begins hour.54 $testhour = 1;55 // Test job run at 1 am.56 $testclass = new \core\task\scheduled_test_task();57 // All fields default to '*'.58 $testclass->set_hour($testhour);59 $testclass->set_minute('0');60 // Next valid time should be 1am of the next day.61 $nexttime = $testclass->get_next_scheduled_time();62 $oneamdate = new DateTime('now', new DateTimeZone('Europe/London'));63 $oneamdate->setTime($testhour, 0, 0);64 // Once a year (currently last Sunday of March), when changing to Daylight Saving Time,65 // Europe/London 01:00 simply doesn't exists because, exactly at 01:00 the clock66 // is advanced by one hour and becomes 02:00. When that happens, the DateInterval67 // calculations cannot be to advance by 1 day, but by one less hour. That is exactly when68 // the next scheduled run will happen (next day 01:00).69 $isdaylightsaving = false;70 if ($testhour < (int)$oneamdate->format('H')) {71 $isdaylightsaving = true;72 }73 // Make it 1 am tomorrow if the time is after 1am.74 if ($oneamdate->getTimestamp() < time()) {75 $oneamdate->add(new DateInterval('P1D'));76 if ($isdaylightsaving) {77 // If today is Europe/London Daylight Saving Time Begins, expectation is 1 less hour.78 $oneamdate->sub(new DateInterval('PT1H'));79 }80 }81 $oneam = $oneamdate->getTimestamp();82 $this->assertEquals($oneam, $nexttime, 'Next scheduled time is 1am.');83 // Disabled flag does not affect next time.84 $testclass->set_disabled(true);85 $nexttime = $testclass->get_next_scheduled_time();86 $this->assertEquals($oneam, $nexttime, 'Next scheduled time is 1am.');87 // Now test for job run every 10 minutes.88 $testclass = new \core\task\scheduled_test_task();89 // All fields default to '*'.90 $testclass->set_minute('*/10');91 // Next valid time should be next 10 minute boundary.92 $nexttime = $testclass->get_next_scheduled_time();93 $minutes = ((intval(date('i') / 10))+1) * 10;94 $nexttenminutes = mktime(date('H'), $minutes, 0);95 $this->assertEquals($nexttenminutes, $nexttime, 'Next scheduled time is in 10 minutes.');96 // Disabled flag does not affect next time.97 $testclass->set_disabled(true);98 $nexttime = $testclass->get_next_scheduled_time();99 $this->assertEquals($nexttenminutes, $nexttime, 'Next scheduled time is in 10 minutes.');100 // Test hourly job executed on Sundays only.101 $testclass = new \core\task\scheduled_test_task();102 $testclass->set_minute('0');103 $testclass->set_day_of_week('7');104 $nexttime = $testclass->get_next_scheduled_time();105 $this->assertEquals(7, date('N', $nexttime));106 $this->assertEquals(0, date('i', $nexttime));107 // Test monthly job108 $testclass = new \core\task\scheduled_test_task();109 $testclass->set_minute('32');110 $testclass->set_hour('0');111 $testclass->set_day('1');112 $nexttime = $testclass->get_next_scheduled_time();113 $this->assertEquals(32, date('i', $nexttime));114 $this->assertEquals(0, date('G', $nexttime));115 $this->assertEquals(1, date('j', $nexttime));116 }117 public function test_timezones() {118 global $CFG, $USER;119 // The timezones used in this test are chosen because they do not use DST - that would break the test.120 $this->resetAfterTest();121 $this->setTimezone('Asia/Kabul');122 $testclass = new \core\task\scheduled_test_task();123 // Scheduled tasks should always use servertime - so this is 03:30 GMT.124 $testclass->set_hour('1');125 $testclass->set_minute('0');126 // Next valid time should be 1am of the next day.127 $nexttime = $testclass->get_next_scheduled_time();128 // GMT+05:45.129 $USER->timezone = 'Asia/Kathmandu';130 $userdate = userdate($nexttime);131 // Should be displayed in user timezone.132 // I used http://www.timeanddate.com/worldclock/fixedtime.html?msg=Moodle+Test&iso=20160502T01&p1=113133 // setting my location to Kathmandu to verify this time.134 $this->assertContains('2:15 AM', core_text::strtoupper($userdate));135 }136 public function test_reset_scheduled_tasks_for_component_customised(): void {137 $this->resetAfterTest(true);138 $tasks = \core\task\manager::load_scheduled_tasks_for_component('moodle');139 // Customise a task.140 $task = reset($tasks);141 $task->set_minute('1');142 $task->set_hour('2');143 $task->set_month('3');144 $task->set_day_of_week('4');145 $task->set_day('5');146 $task->set_customised('1');147 \core\task\manager::configure_scheduled_task($task);148 // Now call reset.149 \core\task\manager::reset_scheduled_tasks_for_component('moodle');150 // Fetch the task again.151 $taskafterreset = \core\task\manager::get_scheduled_task(get_class($task));152 // The task should still be the same as the customised.153 $this->assertTaskEquals($task, $taskafterreset);154 }155 public function test_reset_scheduled_tasks_for_component_deleted(): void {156 global $DB;157 $this->resetAfterTest(true);158 // Delete a task to simulate the fact that its new.159 $tasklist = \core\task\manager::load_scheduled_tasks_for_component('moodle');160 // Note: This test must use a task which does not use any random values.161 $task = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);162 $DB->delete_records('task_scheduled', array('classname' => '\\' . trim(get_class($task), '\\')));163 $this->assertFalse(\core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class));164 // Now call reset on all the tasks.165 \core\task\manager::reset_scheduled_tasks_for_component('moodle');166 // Assert that the second task was added back.167 $taskafterreset = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);168 $this->assertNotFalse($taskafterreset);169 $this->assertTaskEquals($task, $taskafterreset);170 $this->assertCount(count($tasklist), \core\task\manager::load_scheduled_tasks_for_component('moodle'));171 }172 public function test_reset_scheduled_tasks_for_component_changed_in_source(): void {173 $this->resetAfterTest(true);174 // Delete a task to simulate the fact that its new.175 // Note: This test must use a task which does not use any random values.176 $task = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);177 // Get a copy of the task before maing changes for later comparison.178 $taskbeforechange = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);179 // Edit a task to simulate a change in its definition (as if it was not customised).180 $task->set_minute('1');181 $task->set_hour('2');182 $task->set_month('3');183 $task->set_day_of_week('4');184 $task->set_day('5');185 \core\task\manager::configure_scheduled_task($task);186 // Fetch the task out for comparison.187 $taskafterchange = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);188 // The task should now be different to the original.189 $this->assertTaskNotEquals($taskbeforechange, $taskafterchange);190 // Now call reset.191 \core\task\manager::reset_scheduled_tasks_for_component('moodle');192 // Fetch the task again.193 $taskafterreset = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);194 // The task should now be the same as the original.195 $this->assertTaskEquals($taskbeforechange, $taskafterreset);196 }197 /**198 * Tests that the reset function deletes old tasks.199 */200 public function test_reset_scheduled_tasks_for_component_delete() {201 global $DB;202 $this->resetAfterTest(true);203 $count = $DB->count_records('task_scheduled', array('component' => 'moodle'));204 $allcount = $DB->count_records('task_scheduled');205 $task = new \core\task\scheduled_test_task();206 $task->set_component('moodle');207 $record = \core\task\manager::record_from_scheduled_task($task);208 $DB->insert_record('task_scheduled', $record);209 $this->assertTrue($DB->record_exists('task_scheduled', array('classname' => '\core\task\scheduled_test_task',210 'component' => 'moodle')));211 $task = new \core\task\scheduled_test2_task();212 $task->set_component('moodle');213 $record = \core\task\manager::record_from_scheduled_task($task);214 $DB->insert_record('task_scheduled', $record);215 $this->assertTrue($DB->record_exists('task_scheduled', array('classname' => '\core\task\scheduled_test2_task',216 'component' => 'moodle')));217 $aftercount = $DB->count_records('task_scheduled', array('component' => 'moodle'));218 $afterallcount = $DB->count_records('task_scheduled');219 $this->assertEquals($count + 2, $aftercount);220 $this->assertEquals($allcount + 2, $afterallcount);221 // Now check that the right things were deleted.222 \core\task\manager::reset_scheduled_tasks_for_component('moodle');223 $this->assertEquals($count, $DB->count_records('task_scheduled', array('component' => 'moodle')));224 $this->assertEquals($allcount, $DB->count_records('task_scheduled'));225 $this->assertFalse($DB->record_exists('task_scheduled', array('classname' => '\core\task\scheduled_test2_task',226 'component' => 'moodle')));227 $this->assertFalse($DB->record_exists('task_scheduled', array('classname' => '\core\task\scheduled_test_task',228 'component' => 'moodle')));229 }230 public function test_get_next_scheduled_task() {231 global $DB;232 $this->resetAfterTest(true);233 // Delete all existing scheduled tasks.234 $DB->delete_records('task_scheduled');235 // Add a scheduled task.236 // A task that runs once per hour.237 $record = new stdClass();238 $record->blocking = true;239 $record->minute = '0';240 $record->hour = '0';241 $record->dayofweek = '*';242 $record->day = '*';243 $record->month = '*';244 $record->component = 'test_scheduled_task';245 $record->classname = '\core\task\scheduled_test_task';246 $DB->insert_record('task_scheduled', $record);247 // And another one to test failures.248 $record->classname = '\core\task\scheduled_test2_task';249 $DB->insert_record('task_scheduled', $record);250 // And disabled test.251 $record->classname = '\core\task\scheduled_test3_task';252 $record->disabled = 1;253 $DB->insert_record('task_scheduled', $record);254 $now = time();255 // Should get handed the first task.256 $task = \core\task\manager::get_next_scheduled_task($now);257 $this->assertInstanceOf('\core\task\scheduled_test_task', $task);258 $task->execute();259 \core\task\manager::scheduled_task_complete($task);260 // Should get handed the second task.261 $task = \core\task\manager::get_next_scheduled_task($now);262 $this->assertInstanceOf('\core\task\scheduled_test2_task', $task);263 $task->execute();264 \core\task\manager::scheduled_task_failed($task);265 // Should not get any task.266 $task = \core\task\manager::get_next_scheduled_task($now);267 $this->assertNull($task);268 // Should get the second task (retry after delay).269 $task = \core\task\manager::get_next_scheduled_task($now + 120);270 $this->assertInstanceOf('\core\task\scheduled_test2_task', $task);271 $task->execute();272 \core\task\manager::scheduled_task_complete($task);273 // Should not get any task.274 $task = \core\task\manager::get_next_scheduled_task($now);275 $this->assertNull($task);276 // Check ordering.277 $DB->delete_records('task_scheduled');278 $record->lastruntime = 2;279 $record->disabled = 0;280 $record->classname = '\core\task\scheduled_test_task';281 $DB->insert_record('task_scheduled', $record);282 $record->lastruntime = 1;283 $record->classname = '\core\task\scheduled_test2_task';284 $DB->insert_record('task_scheduled', $record);285 // Should get handed the second task.286 $task = \core\task\manager::get_next_scheduled_task($now);287 $this->assertInstanceOf('\core\task\scheduled_test2_task', $task);288 $task->execute();289 \core\task\manager::scheduled_task_complete($task);290 // Should get handed the first task.291 $task = \core\task\manager::get_next_scheduled_task($now);292 $this->assertInstanceOf('\core\task\scheduled_test_task', $task);293 $task->execute();294 \core\task\manager::scheduled_task_complete($task);295 // Should not get any task.296 $task = \core\task\manager::get_next_scheduled_task($now);297 $this->assertNull($task);298 }299 public function test_get_broken_scheduled_task() {300 global $DB;301 $this->resetAfterTest(true);302 // Delete all existing scheduled tasks.303 $DB->delete_records('task_scheduled');304 // Add a scheduled task.305 // A broken task that runs all the time.306 $record = new stdClass();307 $record->blocking = true;308 $record->minute = '*';309 $record->hour = '*';310 $record->dayofweek = '*';311 $record->day = '*';312 $record->month = '*';313 $record->component = 'test_scheduled_task';314 $record->classname = '\core\task\scheduled_test_task_broken';315 $DB->insert_record('task_scheduled', $record);316 $now = time();317 // Should not get any task.318 $task = \core\task\manager::get_next_scheduled_task($now);319 $this->assertDebuggingCalled();320 $this->assertNull($task);321 }322 /**323 * Tests the use of 'R' syntax in time fields of tasks to get324 * tasks be configured with a non-uniform time.325 */326 public function test_random_time_specification() {327 // Testing non-deterministic things in a unit test is not really328 // wise, so we just test the values have changed within allowed bounds.329 $testclass = new \core\task\scheduled_test_task();330 // The test task defaults to '*'.331 $this->assertInternalType('string', $testclass->get_minute());332 $this->assertInternalType('string', $testclass->get_hour());333 // Set a random value.334 $testclass->set_minute('R');335 $testclass->set_hour('R');336 $testclass->set_day_of_week('R');337 // Verify the minute has changed within allowed bounds.338 $minute = $testclass->get_minute();339 $this->assertInternalType('int', $minute);340 $this->assertGreaterThanOrEqual(0, $minute);341 $this->assertLessThanOrEqual(59, $minute);342 // Verify the hour has changed within allowed bounds.343 $hour = $testclass->get_hour();344 $this->assertInternalType('int', $hour);345 $this->assertGreaterThanOrEqual(0, $hour);346 $this->assertLessThanOrEqual(23, $hour);347 // Verify the dayofweek has changed within allowed bounds.348 $dayofweek = $testclass->get_day_of_week();349 $this->assertInternalType('int', $dayofweek);350 $this->assertGreaterThanOrEqual(0, $dayofweek);351 $this->assertLessThanOrEqual(6, $dayofweek);352 }353 /**354 * Test that the file_temp_cleanup_task removes directories and355 * files as expected.356 */357 public function test_file_temp_cleanup_task() {358 global $CFG;359 $backuptempdir = make_backup_temp_directory('');360 // Create directories.361 $dir = $backuptempdir . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses';362 mkdir($dir, 0777, true);363 // Create files to be checked and then deleted.364 $file01 = $dir . DIRECTORY_SEPARATOR . 'sections.xml';365 file_put_contents($file01, 'test data 001');366 $file02 = $dir . DIRECTORY_SEPARATOR . 'modules.xml';367 file_put_contents($file02, 'test data 002');368 // Change the time modified for the first file, to a time that will be deleted by the task (greater than seven days).369 touch($file01, time() - (8 * 24 * 3600));370 $task = \core\task\manager::get_scheduled_task('\\core\\task\\file_temp_cleanup_task');371 $this->assertInstanceOf('\core\task\file_temp_cleanup_task', $task);372 $task->execute();373 // Scan the directory. Only modules.xml should be left.374 $filesarray = scandir($dir);375 $this->assertEquals('modules.xml', $filesarray[2]);376 $this->assertEquals(3, count($filesarray));377 // Change the time modified on modules.xml.378 touch($file02, time() - (8 * 24 * 3600));379 // Change the time modified on the courses directory.380 touch($backuptempdir . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR .381 'courses', time() - (8 * 24 * 3600));382 // Run the scheduled task to remove the file and directory.383 $task->execute();384 $filesarray = scandir($backuptempdir . DIRECTORY_SEPARATOR . 'backup01');385 // There should only be two items in the array, '.' and '..'.386 $this->assertEquals(2, count($filesarray));387 // Change the time modified on all of the files and directories.388 $dir = new \RecursiveDirectoryIterator($CFG->tempdir);389 // Show all child nodes prior to their parent.390 $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);391 for ($iter->rewind(); $iter->valid(); $iter->next()) {392 if ($iter->isDir() && !$iter->isDot()) {393 $node = $iter->getRealPath();394 touch($node, time() - (8 * 24 * 3600));395 }396 }397 // Run the scheduled task again to remove all of the files and directories.398 $task->execute();399 $filesarray = scandir($CFG->tempdir);400 // All of the files and directories should be deleted.401 // There should only be three items in the array, '.', '..' and '.htaccess'.402 $this->assertEquals([ '.', '..', '.htaccess' ], $filesarray);403 }404 /**405 * Test that the function to clear the fail delay from a task works correctly.406 */407 public function test_clear_fail_delay() {408 $this->resetAfterTest();409 // Get an example task to use for testing. Task is set to run every minute by default.410 $taskname = '\core\task\send_new_user_passwords_task';411 // Pretend task started running and then failed 3 times.412 $before = time();413 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');414 for ($i = 0; $i < 3; $i ++) {415 $task = \core\task\manager::get_scheduled_task($taskname);416 $lock = $cronlockfactory->get_lock('\\' . get_class($task), 10);417 $task->set_lock($lock);418 \core\task\manager::scheduled_task_failed($task);419 }420 // Confirm task is now delayed by several minutes.421 $task = \core\task\manager::get_scheduled_task($taskname);422 $this->assertEquals(240, $task->get_fail_delay());423 $this->assertGreaterThan($before + 230, $task->get_next_run_time());424 // Clear the fail delay and re-get the task.425 \core\task\manager::clear_fail_delay($task);426 $task = \core\task\manager::get_scheduled_task($taskname);427 // There should be no delay and it should run within the next minute.428 $this->assertEquals(0, $task->get_fail_delay());429 $this->assertLessThan($before + 70, $task->get_next_run_time());430 }431 /**432 * Assert that the specified tasks are equal.433 *434 * @param \core\task\task_base $task435 * @param \core\task\task_base $comparisontask436 */437 public function assertTaskEquals(\core\task\task_base $task, \core\task\task_base $comparisontask): void {438 // Convert both to an object.439 $task = \core\task\manager::record_from_scheduled_task($task);440 $comparisontask = \core\task\manager::record_from_scheduled_task($comparisontask);441 // Reset the nextruntime field as it is intentionally dynamic.442 $task->nextruntime = null;443 $comparisontask->nextruntime = null;444 $args = array_merge(445 [446 $task,447 $comparisontask,448 ],449 array_slice(func_get_args(), 2)450 );451 call_user_func_array([$this, 'assertEquals'], $args);452 }453 /**454 * Assert that the specified tasks are not equal.455 *456 * @param \core\task\task_base $task457 * @param \core\task\task_base $comparisontask458 */459 public function assertTaskNotEquals(\core\task\task_base $task, \core\task\task_base $comparisontask): void {460 // Convert both to an object.461 $task = \core\task\manager::record_from_scheduled_task($task);462 $comparisontask = \core\task\manager::record_from_scheduled_task($comparisontask);463 // Reset the nextruntime field as it is intentionally dynamic.464 $task->nextruntime = null;465 $comparisontask->nextruntime = null;466 $args = array_merge(467 [468 $task,469 $comparisontask,470 ],471 array_slice(func_get_args(), 2)472 );473 call_user_func_array([$this, 'assertNotEquals'], $args);474 }475 /**476 * Assert that the lastruntime column holds an original value after a scheduled task is reset.477 */478 public function test_reset_scheduled_tasks_for_component_keeps_original_lastruntime(): void {479 global $DB;480 $this->resetAfterTest(true);481 // Set lastruntime for the scheduled task.482 $DB->set_field('task_scheduled', 'lastruntime', 123456789, ['classname' => '\core\task\session_cleanup_task']);483 // Reset the task.484 \core\task\manager::reset_scheduled_tasks_for_component('moodle');485 // Fetch the task again.486 $taskafterreset = \core\task\manager::get_scheduled_task(core\task\session_cleanup_task::class);487 // Confirm, that lastruntime is still in place.488 $this->assertEquals(123456789, $taskafterreset->get_last_run_time());489 }490}...

Full Screen

Full Screen

function.php

Source:function.php Github

copy

Full Screen

1<?php2/**3 * Created by PhpStorm.4 * User: wushangkun5 * Date: 2020/12/266 * Time: 6:29 PM7 */8/// 1. 函数中的函数9//10// PHP 中的所有函数和类都具有全局作用域,可以定义在一个函数之内而在之外调用,反之亦然。11//12// PHP 不支持函数重载,也不可能取消定义或者重定义已声明的函数。13function foo()14{15 function bar()16 {17 echo "I don't exist until foo() is called.\n";18 }19}20/* 现在还不能调用bar()函数,因为它还不存在 */21foo();22/* 现在可以调用bar()函数了,因为foo()函数23 的执行使得bar()函数变为已定义的函数 */24bar();25function recursion($a)26{27 if ($a < 20) {28 echo "$a\n";29 recursion($a + 1);30 }31}32recursion(10); # 10 11 12 13 14 15 16 17 18 1933echo "<br/>";34// 1.1 向函数传递数组35// 默认情况下,函数参数通过 值传递36function takes_array($input)37{38 echo "$input[0] + $input[1] = ", $input[0]+$input[1]; # 23 + 24 = 4739}40takes_array([23, 24]);41echo "<br/>";42// 1.2 通过引用传递参数43function add_some_extras(&$p)44{45 // 默认情况下,函数参数通过值传递(因而即使在函数内部改变参数的值,它并不会改变函数外部的值)46 // 如果希望允许函数修改它的参数值,必须通过引用传递参数。47 $p .= 'and something extra.';48}49$str = 'This is a string, ';50add_some_extras($str);51echo $str; # 打印出 'This is a string, and something extra.'52echo "<br/>";53// 1.3 在函数中使用默认参数54function makecoffee($type = "cappuccino")55{56 return "Making a cup of $type.\n";57}58echo makecoffee(); # Making a cup of cappuccino.59echo makecoffee(null); # Making a cup of .60echo makecoffee("espresso"); # Making a cup of espresso.61echo "<br/>";62// 1.4 PHP 还允许使用数组 array 和特殊类型 null 作为默认参数63// 默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等。64function makeCoffe2($types = ["cappuccino"], $coffeMaker = NULL)65{66 $device = is_null($coffeMaker) ? "hands" : $coffeMaker;67 return "Making a cup of ".join(", ", $types)." with $device. \n";68}69echo makeCoffe2(); # Making a cup of cappuccino with hands.70echo makeCoffe2(["cappuccino", "lavazza"] , "teapot"); # Making a cup of cappuccino, lavazza with teapot.71/// 注意: 注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧!!!!!72function makeyogurt1($type = "acidophilus", $flavour) # 错误写法❌73{74 return "Making a bowl of $type $flavour.\n";75}76function makeyogurt2($flavour, $type = "acidophilus") # 正确写法✅77{78 return "Making a bowl of $type $flavour.\n";79}80/// 2. 可变数量的参数列表81// 2.1 使用 ... 来访问变量参数82function sum(...$numbers)83{84 $total = 0;85 foreach ($numbers as $n)86 {87 $total += $n;88 }89 return $total;90}91echo sum(1, 2, 3, 4, 5); # 1592// 2.2 使用 ... 来传递参数93function add($a, $b)94{95 return $a + $b;96}97// 可以使用 ... 语法来传递 array 或 Traversable 做为参数到函数中:98echo add(...[1, 2]); # 399$a = [1, 2];100echo add(...$a); # 3101echo "<br/>";102// 在 ... 前指定正常的位置参数103// 可以在 ... 标记前添加一个 类型声明。104function total_intervals($unit, DateInterval ...$intervals)105{106 $time = 0;107 foreach ($intervals as $interval)108 {109 $time += $interval->$unit;110 }111 return $time;112}113$a = DateInterval::createFromDateString('P1D');114$b = DateInterval::createFromDateString('P2D');115echo total_intervals('d', $a, $b).' days'; # 0 days116/// 3. 可变数量的参数列表117// 从函数返回一个引用118function &scalar_ref_inc_x(&$x)119{120 $x++;121 return $x;122}123$x = 1;124$x2 =& scalar_ref_inc_x($x);125scalar_ref_inc_x($x2);126print $x . ', ' . $x2 . "\n"; # 3, 3127/// 4. 可变函数128// 4.1 如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。129function echoit($string)130{131 echo $string;132}133$func = 'echoit';134$func('test'); // This calls echoit()135// 4.2 Variable 方法和静态属性示例136// 当调用静态方法时,函数调用要比静态属性优先:137class TestClass138{139 static $variable = 'static property';140 static function Variable()141 {142 echo 'Method Variable called';143 }144 static function callOtherFunc()145 {146 $func = 'TestClass::funcToCall';147 $func();148 }149}150echo TestClass::$variable; # 打印出 static property151$variable = "Variable";152// 注意: 这将调用TestClass->Variable(),读取此作用域中的$Variable。153TestClass::$variable(); # 打印出 Method Variable called...

Full Screen

Full Screen

testClass

Using AI Code Generation

copy

Full Screen

1$dateInterval = new DateInterval();2$dateInterval->testClass();3$dateInterval = new DateInterval();4$dateInterval->testClass();5Your name to display (optional):6Your name to display (optional):7$dateInterval = new DateInterval();8$dateInterval->testClass();9$dateInterval = new DateInterval();10$dateInterval->testClass();11namespace first;12$dateInterval = new DateInterval();13$dateInterval->testClass();14namespace second;15$dateInterval = new DateInterval();16$dateInterval->testClass();17Your name to display (optio

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Atoum automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Trigger testClass code on LambdaTest Cloud Grid

Execute automation tests with testClass on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful