在类定义之外访问变量和方法 [英] Accessing variables and methods outside of class definitions

查看:65
本文介绍了在类定义之外访问变量和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几行的php文件:

Suppose I have a php file along these lines:

<?php
function abc() {  }

$foo = 'bar';

class SomeClass {  }
?>

SomeClass中使用abc()$foo时,我需要做些特别的事情吗?我正在考虑在函数中使用global来访问在函数外部定义的变量的方法.

Is there anything special I have to do to use abc() and $foo inside SomeClass? I'm thinking along the lines of using global in a function to access variables defined outside the function.

(我是PHP中OOP的新手)

(I'm new to OOP in PHP)

推荐答案

任何类之外的函数都是全局函数,可以从任何地方调用.变量也一样..只是记得要使用全局变量...

functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables...

例如

<?php
function abc() {  }

$foo = 'bar';

class SomeClass {  
 public function tada(){
     global $foo;

     abc();
     echo 'foo and '.$foo;
 }
}
?>

这篇关于在类定义之外访问变量和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆