Jump to content

Recommended Posts

Can't seem to get two classes to work together!

[b]test.class1.php[/b]:
[code]
<?php
class class1 {
public function test1(){
echo "worked!";
}
}

$class1 = new class1;
?>
[/code]

[b]test.class2.php[/b]:
[code]
<?php
class class2 {
public function test2(){
$class1->test1();
}
}

$class2 = new class2;
?>
[/code]

[b]test.php[/b]:
[code]
<?php
require_once("test.class1.php");
require_once("test.class2.php");

$class2->test2();
?>
[/code]


Running "test.php" yields:
[b]Fatal error: Call to a member function test() on a non-object in[/b] [i][filepath][/i][b]test.class2.php on line 4[/b]

Effects are the same if I define the classes in test.php as well. I'm sure it's a stupid mistake of mine, trying to do something php just doesn't like or something that just plain doesn't work.
In method test2() you're using $class1 variable. $class1 variable is defined outside class2. PHP doesn't know anything about it.

http://php.net/manual/en/language.variables.scope.php

[code=php:0]
<?php
class class2 {
public function test2(){
                $class1 = new class1();
$class1->test1();
}
}
[/code]
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.