php - 自动创建myClass的实例

时间:2010-09-10 17:44:53

标签: php class instance

我在/myDir/myClass.php中有一个名为myClass的类。当用户输入url:

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
  }


}   

5 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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


} 

$x = new myClass();

答案 2 :(得分:0)

如果您没有使用

创建实例
$classINstance = new myClass();

然后你没有类实例。这与扩展课程无关。

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

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

我快速搜索了一下,也许看看这个问题接受了答案。看起来像一个可以帮助你的好总结:

OOP

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

答案 3 :(得分:0)

我不明白你要做什么,但也许这会有所帮助:

如果您要创建myClass的实例,但不希望new myClass在任何地方都进行硬编码,则可以使用某种factory(维基百科)

答案 4 :(得分: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 ???

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

相关问题