我试图在函数中创建一个函数:
<?php
class usermanager extends datamanager {
public $id;
public $name;
public $from;
public $twitter;
public $instagram;
public $skype;
public $regIP;
public $lastIP;
public $email;
public function __construct($exists = false,$uid = 0) {
if ($exists == true) {
$this->id = $uid;
$this->name = $this->fetch("SELECT * FROM users WHERE ID = '".$uid."';")->name;
public function getProfile() {
profile();
}
}
else {
public function new($name,$password,$email) {
$this->autocommit(false);
if (!($do = $this->query("INSERT INTO users (name,password,email,rank) VALUES ('".$name."',PASSWORD('".$password."'),'".$email."','0');"))) {
$this->rollback();
return false;
}
else {
$this->commit();
return true;
}
} //end new()
} //end else
} //end __construct()
public function __set() {
trigger_error("Can not edit read-only variable",E_USER_ERROR);
} //end __set()
private function profile() {
$gets = array("twitter","instagram","skype","from");
$fetch = $this->fetch("SELECT * FROM users WHERE ID = '".$this->id."';");
foreach ($gets as $get) {
$this->$get = $fetch->$get;
}
}
} //end class
?>
因为我看到了这个,我以为它会起作用,但我得到了:
分析错误:语法错误,第21行/home/a7405987/usermanager.php中出现意外T_PUBLIC
为什么不起作用?
它现在已经修复,但现在我得到了另一个错误:
调用未定义的函数getProfile()
我该怎么解决这个问题?
在函数中定义函数不是一个好主意。除了类之外,任何函数定义都是自动全局的。public
和private
关键字仅在类定义中有效,而在类函数中无效。如果要从内部函数定义中删除public
,它将运行时不会出错,但结果将是全局定义的getProfile()
。
这个例子应该有助于演示问题:
<?php
class Test {
public function foo() {
function bar() {
echo "Hello from bar!" . PHP_EOL;
}
echo "Hello from foo!" . PHP_EOL;
}
}
$t = new Test;
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from foo!"
// bar() is now defined, but not where you expect
$t->foo();
// PHP Fatal error: Call to undefined method Test::bar()
// $t->bar();
// Works, prints "Hello from bar!"
// Note that this is global scope, not from Test
bar();
演示
不能在成员函数或构造函数中使用修饰符public
/private
/protected
。但是,您可以在方法内部声明一个函数:
public function classMember() {
function doSomething() {
//do something
}
doSomething()
}
对于你的特定问题,你应该初始化你的类,然后检查它是否存在,否则就插入它
不能根据调用的上下文来更改类的结构