user5402
user5402

Reputation: 311

mail function not working in OO PHP

I tried the following:

a.php

<?php
    class Page
    {
        function go(){
            echo "1";
            send();
        }

        function send(){
            mail("[email protected]","subj","hi");
        }
    }
?>

b.php

<?php 
require("a.php");
$page=new Page();
$page->go();
?>

b.php doesn't neither sends a mail nor t echo anything. When I put echo before send in the function go(), PHP echo "1" but doesn't send anything. I thought maybe there's something wrong with the mail() function so I changed b.php to:

<?php 
require("a.php");
$page=new Page();
$page->send();
?>

and everything works fine. What is the problem with the initial code?

Upvotes: 1

Views: 58

Answers (3)

Pupil
Pupil

Reputation: 23958

Change send();

to

$this->send();

send() is a class method not a function, hence it cannot be called without $this in this case.

Upvotes: 1

Cayce K
Cayce K

Reputation: 2338

This isn't a mail function. You are trying to call a function that isn't labeled correctly. In this type you're attempting to call a static function. But the function you're calling is not labeled static. You can fix this a few different ways however.

Your echo doesn't work because it can't find the function you're referencing in go().

// best use
class Page{
    public function go(){
        echo "yay";
        $this->send();
    }
    ...
}

or

// static isn't recommended most often, but this will work.
class Page{
    // same go function
    public static function send(){
       // same
    }
}

Upvotes: 3

mikeb
mikeb

Reputation: 11267

Been awhile since I've used PHP, but you have to use $this to call the send method from a class method. See below:

<?php
    class Page
    {
        function go(){
            echo "1";
            $this->send();  # Added the $this-> to the function call
        }

        function send(){
            mail("[email protected]","subj","hi");
        }
    }
?>

Upvotes: 1

Related Questions