<?php function __autoload($class_name)
{
include_once 'inc/classes/class.' . $class_name . '.inc.php';
}
?>
Right now im using __autoload to automatic load up my classes whenever they are used. But i was thinking, why not automatic initiate the object themself as well, so you dont have to start the object in the pages itself, you could just call the properties of an class without starting the object.
But here i am stuck, i thought i could just do like the example below but its not working, objects are not starting.
<?php
function __autoload($class_name)
{
include_once 'inc/classes/class.' . $class_name . '.inc.php';
'$'.$class_name = new $class_name;
}
?>
This does not make sense. As you say, autoloading happens when the class is referenced.
How is it referenced? Let's see:
With $object = new TheClassName() - there you already have your instance. Why create another one automagically?
With static method calls, access to static properties or constants TheClassName::I_NEED_THIS_CONSTANT - why would I need an automagically created instance if I access a static method/property/constant?
With calls to class_exists() - why would I need an automagially created instance if I just want to check if the class exists?
Try this:
$$class_name = new $class_name();
You can also try using {}. In your example it will be:
${$class_name} = new $class_name;
With ${} you can create dynamic variables like that:
$i = '1';
${'tmp' . $i} = 'Hello world';
echo $tmp1; // Hello world
You should also use spl_autoload_register instead of __autoload (because it can be deprecated or removed in the future).
Related
I'm trying to update my project with namespaces.
Before using namespaces I could easily call a class via a variable like so:
<?php
$className = "Item";
$myClass = new $className();
?>
Now, when using namespaces (with use) I'd expect this to work:
(not working allways meens: 'Can't find class' or smth like this)
<?php
namespace myProject
use myProject\Models
$className = "Item";
$myClass = new $className(); // this class has the namespace myProject\Models
// this doesn't work! (can't find class)
$myClass = new Models\$className();
// nope, doesn't work either
$myClass = new myProject\Models\$className();
// nope
?>
but calling the same class directly - without a variable - IS working
$myClass = new Item();
What I have to do, to make it work is:
<?php
namespace myProject;
use myProject\Models; // unnessecary now
$className = "\\" . __NAMESPACE__ . "\\Models\\" . "Item";
$myClass = new $className();
?>
My question now is:
If I want to call a class via a variable, do I really have to include the whole namespace as a fully qualified name?
EDIT:
I found myself an answer here:
Dynamic namespaced class with alias
I'll keep that question anyway, because I could not find the right answer in first place.
I have a class file: we'll call it class.php. The functionality of that is to grab info from an ini file (yeah, I posted the question about security and was given the great suggestion to use either a config file or an ini file to hold the DB information).
Essentially, my class is this:
<?php
class myClass
{
public function getAttached()
{
$file = "../../myFile.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$hoost = $settings['mysqli']['default_host'];
$useer = $settings['mysqli']['default_user'];
$pazz = $settings['mysqli']['default_pw'];
$dbs = $settings['mysqli']['default_db'];
$con = mysqli_connect($hoost ,$useer, $pazz, $dbs);
return $con;
}
}
$obj = new myClass();
$obj->getAttached();
$vals = $obj->getAttached();
//echo $vals; //didn't know if I should echo this or not.
?>
I want to call this in my somePage.php file to make my "mysqli" connection and go from there...
I tried this:
require_once('class.php');
getAttached();
Obviously that didn't work (I knew it wouldn't but - I did it anyway just to see if "maybe"), so - how do I call that function from my class file in the regular php page?
Any thoughts would be appreciated.
Thanks in advance.
You need to make an instance of the class before calling the functions as they're not static.
require_once('class.php');
$myClass = new myClass();
$myClass-> getAttached();
or, like I said above you could make the function static.
public static function myFunction() {
//etc...
}
Then to call it you would use:
require_once('class.php');
myClass::getAttached();
You have to instanciate your class first, the same way you did it in you class.php file:
$myclass = new myClass();
$myClass->getAttached();
Note that if your method can be used without any relation with your class, you could make it static:
public static function getAttached() {
// ...
}
And use it without having to instanciate your class:
myClass::getAttached();
Your getAttached() method within the myClass ,create the instance for the class and call
the function
$call = new myClass();
$call->getAttached();
Given answers are correct, but if you keep your class file as you posted, you have object already in $obj so there is no need to make new one. If it is just temporary you can ignore my post.
One more thing:
$obj->getAttached(); // this line is not needed, as you call this function in next line
$vals = $obj->getAttached();
I'm attempting to define a __invokeable global instance of a class that contains my application's functions.
Basically I'm trying to create a namespace for my library, and therefore I'm attempting to use a class to hold all my functions/methods.
I don't want to have to include global $class_instance at the top of all my files, because that is ugly.
Also I don't to have to reference the variable like $GLOBALS['myvar'] everywhere.
Personally I find this a real oversight in php.
It appears I can't define super globals like $myFunctionsGlobal
And I can't define variables (well actually constants) in php like myvar=$classInstance.
Namespaces
If namespaces are supposed to solve this issue, why aren't they more widely used?
For example Kohana doesn't use namespaces, along with many other php libraries.
One I'm after:
class _namespace{
public $_function;
function __invoke($arg){
// Function body
echo $arg;
}
function method(){
;
}
}
$N = new _namespace;
$N('someValue');
$N->method();
function myFunc(){
// I don't want global $N;
// I don't want $N = $_GLOBALS['N'];
// I don't want $N = get_instance();
$N('some other value');
}
Solution:
In most other languages like c and js you can only have one object/function per variable name. PHP seems to special allowing you to have namespaces,functions and classes with the same name. I was trying to group all of my functions under one central variable for simplicity and still have the functionality of it being __invokable. In fact a class and a function named the same thing would have provided this functionality.
<?
class R{
static function static_method(){
;
}
function method(){
;
}
}
function R(){;}
R();
R::static_method();
$instance = new R();
$instance->method();
In php5.3 you can emulate a invokable constant with methods by defining a function with the same name as your namespace.
namespace.php
<? namespace Z;
function init($arg=''){
echo $arg;
}
function method(){
echo 'method';
}
function method(){
echo 'method2';
}
othefile.php
include('namespace.php');
function Z($a=null,$b=null){
return Z\init($a,$b);
}
Z('test');
Z\method();
Z\method2();
Here's my new answer for you it works
class _bidon {
static function __invoke($arg){
// Function body
echo $arg;
}
}
$b = new _bidon;
$b('eee');
function myFunc(){
// I don't want global $N;
// I don't want $N = $_GLOBALS['N'];
// I don't want $N = get_instance();
_bidon::__invoke('some other value');
}
myFunc();
but the function will be specific to the class not the object
------ Previous post :
Hi i did not clearly understand but if you have a class created just do :
public static $myFunctionsGlobal;
and whene you want to use it outer than your class you do :
myclassname::$myFunctionsGlobal
and it will be accessible as soon as you include your class
you don't need to create an object because it's a static var you just need to have the class included
You can use a service container.
An example you can find here: Which pattern should I use for my unique instance of the User class? and to deepen If Singletons are bad then why is a Service Container good?
Also namespaces can't help you if you need to have one single instance for your helper objects like you are asking.
Addendum
With the service container I suggest you can still use __invoke.
$obj = app('CallableClass');
$obj(5);
If I declared a class in a controller and want to use it in a model without passing the class' pointer, how can I redeclare that class without the "Fatal error: Class already declared"? If I use the get_declared_classes() function, I see that the class is declared, but how can I get the pointer to that class so that I can use it in the model?
Basically, how can I use a class that's been declared but with no pointer.
Any help would be greatly appreciated.
Thanks in advance!
EDIT: Maybe the word "pointer" was misused. Here's some code
// Controller...one file
$class = new Class();
$model = $this->load_model('example.php');
$model->dosomething();
// Model...example.php
function dosomething() {
// I want to access the class here. Is it only possible to do this by
// passing a $class parameter to the function or can I do it without
// passing it as a variable?
}
I think you're mixing terminology. There's no concept of a pointer anywhere in PHP. References are similar concepts, but that's another topic.
What I think you're trying to do, is use a variable to indicate the class in the model. So, you can use a string. So let's say you want to tell the model to use class Foo, you could inject the class name into the model:
$model = new Model('foo');
Then, inside the constructor:
public function __construct($class) {
$this->className = $class;
}
Then, when you want to use it, just call new:
$class = $this->className;
$obj = new $class();
But note that it has nothing to do with object scope. So you could do it anywhere:
$class = 'Foo';
$obj = new $class;
They say that eval() is evil. I want to avoid the use of the eval() line using proper PHP5 functionality. Given a class name in a static class method, how do I make it return a real object?
class Model {
public static function loadModel($sModelPath) {
if (!(strpos(' ' . $sModelPath, '/')>0)) {
$sModelPath .= '/' . $sModelPath;
}
$sModelName = str_replace('/','_',$sModelPath);
// P is a global var for physical path of the website
require_once(P . '_models/' . $sModelPath . '.php');
eval("\$oObject = new $sModelName" . '();');
return $oObject;
}
}
return new $sModelName();
You can call functions by a dynamic name as well:
$func = "foobar";
$func("baz"); //foobar("baz")
Yep, Kenaniah beat me to it. Gotta type faster...
More info here: http://php.net/manual/en/language.oop5.php, see the first user note.
I know this is a 2 year old question, but I just want to point out, you all missed the question here! All your functions do not return an instantiated class, but a new class. This includes the initial function posted from the questioner!
If you want to return an instantiated class, you have to keep track of your classes and their properties in an array, and return them from there when you require an instance of the class, instead of a re-initialised class.
This method also saves a lot of processing time if your classes do a lot of processing when they are constructed. It's always better to get an instance than to create a new class, unless you really want the class-properties re-initialized. Pay attention!
Try:
$m = new Model();
$m = $m->makeModel();
class Model {
public static function loadModel($sModelPath) {
if (!(strpos(' ' . $sModelPath, '/')>0)) {
$sModelPath .= '/' . $sModelPath;
}
$sModelName = str_replace('/','_',$sModelPath);
// P is a global var for physical path of the website
require_once(P . '_models/' . $sModelPath . '.php');
function makeModel(){
$model = new $sModelName;
return $model;
}
}
}