Arda
Arda

Reputation: 10929

Using class in another class easily with an example

I have a php class that tells time like this (Time.class.php):

<?PHP
class Time {
    var $timestamp;
    function timestamp () {
    $this->timestamp = date('YmdHis');
    return $this->timestamp;
    }
}
?>

What I want to do is to call this time in a different class such as (Test.class.php):

<?PHP
class Test {
    function test (){
    $timestamp = ' '; // <--- the timestamp from the other class
    $hourago = $timestamp - 10000;
    return $hourago;
    }
}
?>

I'm new to PHP classes so I didn't understand what I've read on this subject. From what I've read this can be done with global scope (if its called a scope)?? If you could only show me how to use globals or how to solve a problem like this easily I would appreciate it...

Upvotes: 1

Views: 221

Answers (2)

Alex
Alex

Reputation: 3079

You need to create an instance of the Time class first, then call the method on that instance.

$mytime = new Time();
$timestamp = $mytime->timestamp();

Alternately you could look at static class methods.

Upvotes: 2

dynamic
dynamic

Reputation: 48141

You must use DEPENDENCI INJECTION.

You can pass any references objects in the costructor like this:

   function test ($yourTimeStamp){
       $timestamp = $yourTimeStamp
       [...]
   }

Upvotes: 2

Related Questions