从自我实例中使用#include <string>
#include <iostream>
#include <vector>
#include <typeinfo>
using namespace std;
class Agent{
public:
Agent(string nam){ name = nam; }
~Agent();
protected:
string name;
};
class Human :public Agent{
public:
Human(string nam, int a):Agent(nam){ age = a; }
~Human();
protected:
int age;
};
int main(){
vector<Agent*> agents;
Agent* agent=new Agent("ask");
Human* human=new Human("ask2",18);
Agent* agent2=new Human("AgentAsk",20);
agents.push_back(agent);
agents.push_back(human);
agents.push_back(agent2);
cout << (typeid(agents[1]) == typeid(Agent*)) << endl; /// True
cout << (typeid(agents[1]) == typeid(Human*)) << endl; /// I expect it to be true but its false
cout << (typeid(agents[1]) != typeid(Agent*)) << endl; /// False
return 0;
}
的最佳方式(内存安全)是什么,例如:
call_user_func
或通过引用,例如:
call_user_func(array($this, 'method'));
PS。我知道最好的方法是call_user_func(array(&$this, 'method'));
但是对于框架设计模式的原因(Wordpress),我确实使用$this->method
答案 0 :(得分:1)
如果我知道,它并不重要,因为PHP在两种情况下都会做同样的事情:只会pass reference到同一个对象(该对象不会被克隆)。所以为了简单起见,我没有&
一些测试:
class test
{
function foo() {
call_user_func([$this, 'bar']);
call_user_func([&$this, 'bar']);
}
private function bar() {
echo spl_object_hash($this), PHP_EOL;
}
}
和输出:
php > $obj = new test();
php > $obj->foo();
0000000025077e4a0000000075174bd2
0000000025077e4a0000000075174bd2