File path in classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fistuks
Forum Newbie
Posts: 4
Joined: Wed May 12, 2010 4:10 am

File path in classes

Post 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?
davex
Forum Contributor
Posts: 101
Joined: Sat Feb 27, 2010 4:10 pm
Location: Namibia

Re: File path in classes

Post 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.
fistuks
Forum Newbie
Posts: 4
Joined: Wed May 12, 2010 4:10 am

Re: File path in classes

Post 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...
Post Reply