Best Atoum code snippet using dateInterval.testClass
scheduled_task_test.php
Source:scheduled_task_test.php
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}...
function.php
Source:function.php
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...
testClass
Using AI Code Generation
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
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
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 FreeGet 100 minutes of automation test minutes FREE!!