2010-09-10 87 views
0

我在/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 
    } 


} 

回答

3

的.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(); 
+0

这听起来像我在找什么,但我的后期变量会下降? – bob 2010-09-10 18:17:24

+2

@bob POST的内容将不会被改变。 – Artefacto 2010-09-10 18:25:14

+0

$ classname = str_replace(“。php”,“”,basename($ _ GET ['path'])); – bob 2010-09-10 18:50:45

0
class myClass 
{  
    __construct() 
    { 
    echo "hello World"; 
    myClass_report(); 
    } 
    myClass_report() 
    { 
     // some code here 
    } 


} 

$x = new myClass(); 
+0

...但我不想添加instance_of_myClass = new myClass();因为那样我就无法延续上课 – bob 2010-09-10 17:52:05

0

如果你不与

$classINstance = new myClass(); 

创建一个实例然后,你没有一个类的实例。这与扩展课程无关。

您扩展一个类(我假设你的意思是继承?),然后创建一个扩展父类的新类。要使用这个类,您还需要使用new运算符创建一个新实例。

至少如果您没有使用static关键字为类创建静态方法。

我有一个快速搜索,也许有看看这个问题接受的答案。 Lookd喜欢一个很好的总结,可以帮助你:

OOP

或者我只是不明白你的意思;)

+0

迷人的线程! http://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me – bob 2010-09-10 18:59:19

0

我不明白你想要做什么,但也许这个wi我将尽力帮助:

如果你想创建的myClass的实例,但不希望new myClass无处不硬编码的,你可以使用某种形式的factory(维基百科)。

+0

这是我正在寻找 – bob 2010-09-10 18:19:25

0

使用工厂设计模式:

<?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 ???

应包括类;从来没有用过直接加载到浏览器。

+0

我可以结合这个想法与工厂模式? – bob 2010-09-10 18:31:01

+0

“从来没有用过直接加载” - 你似乎知道你在说什么,但我为什么?我试图转向纯粹的OO范式,所以我说好,我将把所有顶级控制器作为一个类的实例。 – bob 2010-09-10 18:55:54

+1

因为你的班级是你的蓝图。如果你创建一个新的发明,你宁可销售产品,而不是蓝图。所有的类都应该在一个文件中实例化:index.php。你引导一些预先工作,然后班级做这项工作,甚至输出你的网页。 – baklap 2010-09-10 19:08:29