PHP exploding string, strange result

I'm making a tiny autoloader for my kickstarter projects and I have a problem that is a bit confusing me.

I've made a loader class that accepts an argument that must contain underscores to know where the loader have to look after the class. This string contains the path info and the class's name eg.: 'path_to_my_class_myclassname' In the loader class I split up this string by the "_"(underscore) delimeters into an and somehow it always gives back some unexpected array items for example:

if the string would 'first', the array will look like this:

array (size=1)
  0 => string 'first' (length=5)
array (size=1)
  0 => string 'f' (length=1)

Then if I'm using the underscores so the string is: 'youtube_ClassYouTubeAPI' it look like this:

array (size=2)
  0 => string 'youtube' (length=7)
  1 => string 'ClassYouTubeAPI' (length=15)
array (size=1)
  0 => string 'y' (length=1)

You can see that in both example the result array contains the first letter of the input string, but shouldn't.

I was tried the explode('_',$inputstring) and the preg_split('[_]',$inputstring) too but the result was the same.

I would be greatful if someone could help me out. Thanks in advance

===Update===========

Here is the whole code:

<?php
class Autoloader {
    static public function loader($load_input) {

        $load_data = preg_split('[_]',$load_input,0);
        $classname = $load_input[count($load_input)-1];
        $filename = 'classes/'.implode('/',$load_data).'.php'; 
        var_dump($load_data);

        if (file_exists($filename)) {
            include($filename);
            if (class_exists($classname)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('Autoloader::loader');
?>

Upvotes: 0

Views: 167

Answers (1)

Shai
Shai

Reputation: 7315

The splitting works correctly. The problem is this line:

$classname = $load_input[count($load_input)-1];

should be:

$classname = $load_data[count($load_data)-1];

i.e. you need to use $load_data not $load_input!

Otherwise you're asking for the [0] from your input string (which is 'y') rather than the [0] from your exploded array, which is youtube.

Upvotes: 0

Related Questions