Page 1 of 1

File path in classes

Posted: Wed May 12, 2010 4:20 am
by fistuks
Hello,

I'm writing a class (actually my first class) the when declared it gets a file path;

Code: Select all

class myClass {
    public $audioFile;

    function __construct($audioFile) {
        $this->audioFile = $audioFile;
    }

    function copyTo($outFile) {
        copy($this->audioFile,$outFile);
    }
}
But when i do this:

Code: Select all

$a = new myClass("../temp/day.mp3");
$a->copyTo("../test.mp3");
It does nothing...
I figure it is because the class i located in a diffrernt directory but i can't seem to fix it.

I'm sure it is because I'm absolutely green in php and there is a simple solution, i just can't find it.

Help anyone?

Re: File path in classes

Posted: Wed May 12, 2010 4:31 am
by davex
Hi,

I'm pretty sure with functions (and I think with classes) the directory paths are relative to the directory your script is executing in (or whatever the current directory is set to within the PHP context) so where the actual code files reside means nothing.

Try it with absolute paths i.e. /folder/another/file.mp3 for both and see what happens.

What error does copy give you? It may also just be a simple permissions thing.

If the absolute paths work have a look at chddir() to the current script directory maybe.

Cheers,

Dave.

Re: File path in classes

Posted: Wed May 12, 2010 5:26 am
by fistuks
Hey,

I have a problem with the absolut paths.

In order to test i add this before declaring the class:

Code: Select all

if (!defined('MASTER_ROOT')) {
    define('MASTER_ROOT', $_SERVER["DOCUMENT_ROOT"] . '/');
}
And changed the constructor to this:

Code: Select all

$this->audioFile = str_replace("../",MASTER_ROOT,$audioFile);
A made a new function that creates a file:

Code: Select all

function createFile()  {
$file = fopen(MASTER_ROOT."test.txt","w");
fwrite($file,"some text");
fclose($file);
    }
It works great but when i changed the original to:

Code: Select all

function copyTo($outFile)  {
        copy($this->audioFile,MASTER_ROOT."ttt.mp3");
    }
It fails...