Reputation: 6544
<?php
class Statics {
private static $keyword;
public static function __callStatic($name,$args){
self::$keyword = "google";
}
public static function TellMe(){
echo self::$keyword;
}
}
Statics::TellMe();
This is a simple breakdown I tried using __construct
but the way I write the code Statics::TellMe();
I would need to write new
for the __construct
to work. And my private static variable keyword
does not get written without it being called any ideas as to why this is not working??
private static $pathname;
public function __construct($dir = "")
{
set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
if($dir !== "") {
$dir = "/".$dir;
}
self::$pathname = $dir.".htaccess";
if( file_exists(self::$pathname) ) {
self::$htaccess = file_get_contents($dir.".htaccess",true);
self::$htaccess_array = explode("\n",self::$htaccess);
}
}
The self::$patname
is not getting assigned because I am not doing $key = new Key();
so I need a way to do it if I just do Key::get()
or anything like that.
Upvotes: 1
Views: 1276
Reputation: 39099
You do have a misunderstanding in the way __callStatic
is working.
The magic method __callStatic
will act like a fallback method when a static method is unknow to the class.
class Statics {
private static $keyword;
public static function __callStatic($name,$args){
return 'I am '.$name.' and I am called with the arguments : '.implode(','$args);
}
public static function TellMe(){
return 'I am TellMe';
}
}
echo Statics::TellMe(); // print I am TellMe
echo Statics::TellThem(); // print I am TellThem and I am called with the arguments :
echo Statics::TellEveryOne('I','love','them'); // print I am TellEveryOne and I am called with the arguments : I, love, them
So in your case what you could do is :
class Statics {
private static $keyword;
public static function __callStatic($name,$args){
self::$keyword = "google";
return self::$keyword;
}
}
echo Statics::TellMe();
As per your edit :
class Statics{
private static $pathname;
private static $dir;
public function getPathName($dir = "")
// OR public function getPathName($dir = null)
{
if($dir !== self::$dir || self::$pathname === ''){
// OR if($dir !== null || self::$pathname === ''){ -> this way if you do getPathName() a second time, you don't have to pass the param $dir again
self::$dir = $dir;
set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
if($dir !== "") {
$dir = "/".$dir;
}
self::$pathname = $dir.".htaccess";
if( file_exists(self::$pathname) ) {
self::$htaccess = file_get_contents($dir.".htaccess",true);
self::$htaccess_array = explode("\n",self::$htaccess);
}
}
return self::$pathname;
}
}
echo Statics::getPathName('some');
Upvotes: 1