我有三个文件, foo.php , bar.php 和 baz.php ,每个include
'd接下来,如下:
foo.php
<?php
$missile_launch_codes = [
'missileA' => '...',
'missileB' => '...',
'missileC' => '...'
];
bar.php
<?php
require('foo.php');
function try_to_launch($launch_code) {
...
}
function launch_missile($missile_name) {
if (in_array($missile_name, $missile_launch_codes)) {
return try_to_launch($missile_launch_codes[$missile_name]);
} else {
return false;
}
}
baz.php
require('bar.php')
if (...) {
launch_missile(...);
}
baz.php 文件需要能够使用launch_missile()
,但绝对不能访问$missile_launch_codes
。我如何隔离从 foo.php 导入的$missile_launch_codes
以使其不受 baz.php 的控制?
答案 0 :(得分:0)
你可以做的就是Object-oriented方式:
<强> Missile.php 强>
Class Missile
{
private $missile_launch_codes = [
'missileA' => '...',
'missileB' => '...',
'missileC' => '...'
];
private function try_to_launch($launch_code) {
...
}
public function launch_missile($missile_name) {
if (in_array($missile_name, $this->missile_launch_codes)) {
return $this->try_to_launch($this->missile_launch_codes[$missile_name]);
} else {
return false;
}
}
}
Launch.php
include('Missile.php');
Class Launch extends Missile
{
if (...) {
$this->launch_missile(...);
}
}
此处,$missile_launch_codes
只能在Missile
类声明private
时才能访问。
答案 1 :(得分:0)
如果我是你,你需要在OOP中制作它。你可以这样做......
foo.php:
class Foo {
protected function missile_launch_codes() {
return [
'missileA' => '...',
'missileB' => '...',
'missileC' => '...'
];
}
}
bar.php:
class Bar extends Foo {
public function try_to_launch($launch_code) {
...
}
public function launch_missile($missile_name) {
if (in_array($missile_name, $missile_launch_codes)) {
return try_to_launch($this->missile_launch_codes[$missile_name]);
} else {
return false;
}
}
}
baz.php
class Baz extends Bar {
// you cannot access missile_launch_codes() here
}
尝试更多地了解OOP,以便更多地了解我在这里要说的内容..