php - 自动创建myClass的实例
我在/myDir/myClass.php中有一个名为myClass的类。当用户输入url时:php - 自动创建myClass的实例
http://mysite.com/myDir/myClass.php,
我想自动创建一个myClass的实例。我可以用什么技术来做到这一点?这个想法是使用myDir目录作为用户可以直接调用的最高级别的程序,但我不想添加instance_of_myClass = new myClass();
,因为那样我将无法扩展该类。这有意义吗?
class myClass
{
__construct()
{
echo "hello World";
$this->myClass_report();
}
myClass_report()
{
// some code here
}
}
的.htaccess:
#if You have access, omit RewriteBase and put the rule in http.conf,
#with a/in the beginning of the pattern.
RewriteBase/
RewriteCond $0 !=index.php
RewriteRule .* index.php?path=$0 [QSA,B]
的index.php
//check if the file exists and it's allowed
if (!check_if_allowed_path(realpath($_GET['path']))) {
//access denied; check e.g. against the document root or
//something more complex
}
//or use autoload instead
include $_GET['path'];
$classname = basename($_GET['path'], '.php');
$instance = new $classname();
class myClass
{
__construct()
{
echo "hello World";
myClass_report();
}
myClass_report()
{
// some code here
}
}
$x = new myClass();
...但我不想添加instance_of_myClass = new myClass();因为那样我就无法延续上课 – bob 2010-09-10 17:52:05
如果你不与
$classINstance = new myClass();
创建一个实例然后,你没有一个类的实例。这与扩展课程无关。
您扩展一个类(我假设你的意思是继承?),然后创建一个扩展父类的新类。要使用这个类,您还需要使用new运算符创建一个新实例。
至少如果您没有使用static关键字为类创建静态方法。
我有一个快速搜索,也许有看看这个问题接受的答案。 Lookd喜欢一个很好的总结,可以帮助你:
或者我只是不明白你的意思;)
迷人的线程! http://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me – bob 2010-09-10 18:59:19
使用工厂设计模式:
<?php
//Factory.php
include_once('Box.php');
class My_Factory
{
private $this->outcome;
public function __construct()
{
this->outcome = $this->doSomeWeirdShitToSetupTheFactoryAndBlueprintSomething();
}
private function doSomeWeirdShitToSetupTheFactoryAndBlueprintSomething()
{
//1+1
}
public function giveMeAnInstanceOfOutcome()
{
return new My_Box($this->outcome);
}
}
编辑:我看了一遍,我有一个问题: 你为什么要用户输入http://yourl/YourClass.php ???
应包括类;从来没有用过直接加载到浏览器。
这听起来像我在找什么,但我的后期变量会下降? – bob 2010-09-10 18:17:24
@bob POST的内容将不会被改变。 – Artefacto 2010-09-10 18:25:14
$ classname = str_replace(“。php”,“”,basename($ _ GET ['path'])); – bob 2010-09-10 18:50:45