Skip to content

Instantly share code, notes, and snippets.

@grzhan
Created May 12, 2013 12:50
Show Gist options
  • Save grzhan/5563458 to your computer and use it in GitHub Desktop.
Save grzhan/5563458 to your computer and use it in GitHub Desktop.
PHP - OOP - Learning - a "new" statement using string.
<?php
/**
* 要创建一个类的实例,必须使用 new 关键字。
* 当创建新对象时该对象总是被赋值,除非该对象定义了构造函数并且在出错时抛出了一个异常。
* 类应在被实例化之前定义(某些情况下则必须这样)。
* ***如果在 new 之后跟着的是一个包含有类名的字符串,则该类的一个实例被创建。***
* 如果该类属于一个名字空间,则必须使用其完整名称。
* Tip : 在类定义内部,可以用 new self 和 new parent 创建新对象。
*/
class foo
{
public function display(){
echo get_class($this);
}
public function newClass(){
$fooTwo = new self;
$fooTwo->display();
}
}
$className = 'foo';
$instance = new $className();
$instance->newClass();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment