
PHP不同文件中变量的传递问题
一个class文件test.class.php:<?php//test.class.phpclasstest{public$var1=111;functionxxx(){...
一个class文件test.class.php:
<?php
//test.class.php
class test{
public $var1 = 111;
function xxx(){
$this->var1 = 222;
}
function yyy(){
echo $this-var1;
}
}
两个执行文件test1.php和test2.php
<?php
//test1.php
include('test.class.php');
$x = new test;
$x->xxx();
?>
<?php
//test2.php
include('test.calss.php');
$y = new test;
$y->yyy();
>
先执行test1.php,再执行test2.php,我想得到的结果是222,结果不是,请问应该怎么做才能得到222这个值?
var1这个变量不一定要是类的成员.
大致的意思其实就是要在类的一个方法中给一个变量赋值,然后在其他方法中可以调用这个变量,可能很多不同文件去引用它.我知道用SESSION是可以做到的,还有其他方法没有?我想知道其他实现方法. 展开
<?php
//test.class.php
class test{
public $var1 = 111;
function xxx(){
$this->var1 = 222;
}
function yyy(){
echo $this-var1;
}
}
两个执行文件test1.php和test2.php
<?php
//test1.php
include('test.class.php');
$x = new test;
$x->xxx();
?>
<?php
//test2.php
include('test.calss.php');
$y = new test;
$y->yyy();
>
先执行test1.php,再执行test2.php,我想得到的结果是222,结果不是,请问应该怎么做才能得到222这个值?
var1这个变量不一定要是类的成员.
大致的意思其实就是要在类的一个方法中给一个变量赋值,然后在其他方法中可以调用这个变量,可能很多不同文件去引用它.我知道用SESSION是可以做到的,还有其他方法没有?我想知道其他实现方法. 展开
4个回答
展开全部
用单例
class test{
public static $instance = null;
protected $val = 123;
public static getConn(){
if(self::$instance === null){
self::$instance = new self();
}
return self:$instance;
}
public function x()
{
$this -> val = 321;
}
public function y(){
return $this -> val;
}
}
下面两个文件分别在引用的时候,不用new了
直接include进来之后
$a = test::getConn();
$a -> x();
$b = test::getConn();
$b -> y();
追问
这个方法还是只能在同一个文件内生效,分成两个文件来调用还是不行的.
追答
额,你想两次请求中间传递参数。那只能用cookie或者session,或者把参数放在链接里,or写入数据库或者文件。没有其他方法可以想了。
2014-01-20
展开全部
你运行 test2 的时候 $y 是 new 的 test.class ,和 test1没有半毛钱关系啊
cookies、session
再或者
test2 里 include("test1.php");
cookies、session
再或者
test2 里 include("test1.php");
追问
这个跟new test几次应该没什么关系,如果test1和test2合并在一个文件里面就能够得到222,在test2里面include("test1.php")不知道行不行,但是这样做项目好像不太合适,不好维护的,这答案不是我想要的哟
追答
你的test1 和 test2 之间没有存在任何流程或逻辑上的因果顺序关联
而你又拒绝 session 和 cookies 来共享两个脚本之间共享变量参数的传递
这是无解的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用单例模式来设计你的类
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
不想用SESSION或cookie,那就得用get或post, 应该你这二个文件的类根本都没有任何关系
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询