我想将值($ login)从cookie传递给$ dir。 的 file.php
<?php
class File {
public $filename;
public $login;
public $dir;
public function __construct() {
$this->login = $_COOKIE['login'];
this->dir = "userFiles/" . $this->login . "/";
$createDir="./userFiles/".$login;
if (!is_dir($createDir)){
mkdir($createDir,0777,true);
}
$action = isset($_POST['action']) ? $_POST['action'] : false;
$this->filename = isset($_POST['filename']) ? $_POST['filename'] : false;
}
private function save() {
$content = isset($_POST['content']) ? $_POST['content'] : '';
file_put_contents($this->dir.$this->filename, urldecode($content));
}
}
$file = new File();
?>
这是整个代码。文件名和操作变量由index.php页面中的ajax传递。
index.php 这是将数据发送到
的主页面<?php
if ( ! isset($_COOKIE['login']) ) {
echo "Need to log in first";
header("refresh:2;url=login.php");
exit;
}
?>
<!doctype html>
<html>
<head>
<title>Editor</title>
</head>
<body>
<textarea id="code" name="code">code goes here</textarea>
<br/><button id="save">save</button>
<input type="text" id="filename" value="test.txt"><br>
<script src="JavaScript/jquery.js"></script>
<script>
var url = 'file.php';
$("#save").click(function() {
$.ajax({
url : url,
type: 'post',
xhrFields: {
withCredentials: true
},
data : {
filename : $("#filename").val(),
action : 'save',
content : encodeURIComponent($('#code').val())
}
});
});
</script>
</body>
</html>
答案 0 :(得分:3)
这应该适合你:
(您只能在constant values
中将class members
分配给class definition
!所以您必须在constructor
或function
中分配它!你必须使用$this->
来访问类的变量
举个例子:
class File {
public $filename;
public $login; //problem here
public $dir; // $login is not getting here. It works if I remove $login.
public function __construct() {
$this->login = $_COOKIE['login'];
$this->dir="userFiles/".$this->login."/";
}
}
$obj = new File();
echo $obj->login . "<br />";
echo $obj->dir;
所以你的整个代码应该是这样的:
class File {
public $filename;
public $login;
public $dir;
public function __construct() {
$this->login = $_COOKIE['login'];
$this->dir = "userFiles/" . $this->login . "/";
if (!is_dir($createDir)){
mkdir($createDir,0777,true);
}
}
}
有关详细信息,请参阅:http://php.net/manual/en/language.oop5.properties.php