php的魔术变量__METHOD__、__FUNCTION、__DIR__、__f

在php中提供了__FILE__、__DIR__、__LINE__、__CLASS__、__NAMESPACE__、__METHOD__、__FUNCTION__等魔术变量,其中:

__FILE__:返回该文件的完整路径和文件名。

__DIR__:返回文件的目录。

__LINE__:返回当前文件的行数。

__CLASS__:返回类名。

__NAMESPACE__:返回当前命名空间的名称。

__METHOD__:返回类的方法名。

__FUNCTION__:返回当前函数名。


<?php

	// Set namespace (works only with PHP 5.3+)
	namespace TestProject;

	// This prints file full path and name
	echo "This file full path and file name is '" . __FILE__ . "'.\n";

	// This prints file full path, without file name
	echo "This file full path is '" . __DIR__ . "'.\n";

	// This prints current line number on file
	echo "This is line number " . __LINE__ . ".\n";

	// Really simple basic test function
	function test_function_magic_constant() {
		echo "This is from '" . __FUNCTION__ . "' function.\n";
	}

	// Prints function and used namespace
	test_function_magic_constant();

	// Really simple class for testing magic constants
	class TestMagicConstants {
		// Prints class name
		public function printClassName() {
			echo "This is " . __CLASS__ . " class.\n";
		}

		// Prints class and method name
		public function printMethodName() {
			echo "This is " . __METHOD__ . " method.\n";
		}

		// Prints function name
		public function printFunction() {
			echo "This is function '" . __FUNCTION__ . "' inside class.\n";
		}

		// Prints namespace name (works only with PHP 5.3)
		public function printNamespace() {
			echo "Namespace name is '" . __NAMESPACE__ . "'.\n";
		}
	}

	// Create new TestMagicConstants class
	$test_magic_constants = new TestMagicConstants;

	// This prints class name and used namespace
	$test_magic_constants->printClassName();

	// This prints method name and used namespace
	$test_magic_constants->printMethodName();

	// This prints function name inside class and used namespace
	// same as method name, but without class
	$test_magic_constants->printFunction();

	// This prints namespace name (works only with PHP 5.3)
	$test_magic_constants->printNamespace();

?>
输出结果:

This file full path and file name is '/tmp/magic_constants/magic.php'.
This file full path is '/tmp/magic_constants'.
This is line number 13.
This is from 'TestProject\test_function_magic_constant' function.
This is TestProject\TestMagicConstants class.
This is TestProject\TestMagicConstants::printMethodName method.
This is function 'printFunction' inside class.
Namespace name is 'TestProject'.

这就是php中的相关魔术变量,在php的相关开发中,使用魔术变量将会使得开发变得更加的简便。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值