php - automatically create an instance of myClass
I have a class called myClass in /myDir/myClass.php. When user types url:
http://mysite.com/myDir/myClass.php,
I want to automatically create an instance of myClass. What techniq开发者_开发问答ue can I use to do this? the idea is to use myDir directory as top level of programs that user can call directly, but I don't want to add instance_of_myClass = new myClass();
because then I won't be able to extend the class. Does this make sense?
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();
I don't understand what you're trying to do, but maybe this will help:
If you want to create an instance of myClass
, but don't want the new myClass
to be hard-coded everywhere, you could use a factory (wikipedia) of some kind.
If you are not creating an instance with
$classINstance = new myClass();
Then you don't have a class instance. That has nothing to do with extending a class.
You extend a class (i assume you mean inheritance?), then you create a new class that extends a parent class. To use this class you also create a new instance with the new operator.
At least if you are not using the static keyword to create static methods for a class.
I had a quick search, maybe have a look at this questions accepted answer. Lookd like a good summary that could help you:
OOP
Or i just didn't understand what you meant ;)
Use the factory design pattern:
<?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);
}
}
Edit: I read it again and I have one question: Why do you want a user to type http://yourl/YourClass.php ???
Classes should be included; never ever ever used to load directly to the browser.
精彩评论