Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a class:
class Test {
public function someFunction()
{
require('SomeOtherClass.php');
}
}
I can't understand how php requires the class here if another class physically can't be inside a function of a class? how php does this? where php puts the class then?
This is in the documentation for include:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. (emphasis added)
require is identical to include in virtually all respects, including this one.
Use the following in the class:
class Test {
public $other_class;
function __construct() {
$this->other_class = new other_class();
}
public function someFunction() {
$this->other_class;
}
}
To use this. Inlcude your classes like this:
spl_autoload_register(function($class) {
include_once 'classes/'.$class.'.php';
});
Use that function in a file that is included everywhere
This is perfectly valid code:
function foo() {
class Foobar {
function speak() {
echo "Hi";
}
}
$obj = new Foobar();
$obj->speak();
}
// $obj = new Foobar(); // Will fail, as Foobar will be defined the global scope when running foo();
foo();
$obj = new Foobar(); // Will be OK, now the class is defined in the global scope
//foo(); // Fatal error: Cannot redeclare class Foobar
The output is:
Hi
For details see documentation.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
Is there a way to implement this idea
class Test{
public function test(){
return include 'test.php';
}
}
test.php
<?php
// process the functions here (including queries , etc)
return 1;
?>
Test
$test = new Test();
echo $test->test();
Basically, it's a combination of OOP and Procedural approach. The main goal here is to separate the process of the functions and put it on another file. The purpose is lessen the lines of the code from the class and make it easier to trace instead of scrolling to 1000+ lines of codes.
PS. I'm sorry for the title. I am not sure if this is possible but I hope you could give me idea.
Thanks and Have a nice day!
what you can do is to aggregate an other class (which can sit in an other file) and call a method of this:
Main Class: Test.php
<?php
use namespace\path\to\OtherClass;
//or require_once("path/to/OtherClass.php");
class Test
{
public function test()
{
$otherClass = new OtherClass();
return $otherClass->otherCall();
}
}
while the other class will look like this (OtherClass.php):
<?php
class OtherClass
{
public function otherCall()
{
return "some value";
}
}
Further ...
if you have a class which you want to mix in your classes, you can use the concept of mixins, which are called traits in php.
The OtherClass.php will change to
<?php
trait OtherClass
{
public function otherCall()
{
return "some value";
}
}
and the Test.php class would change to:
<?php
use namespace\path\to\OtherClass;
//or require_once("path/to/OtherClass.php");
class Test
{
use OtherClass;
public function test()
{
return $this->otherCall();
}
}
If you are new to OOP or Programming I can reccomand two books by Robert Martin:
"Clean Code" and "Clean Architecture".
And to get better in PhP I can recommand this website: https://phptherightway.com/
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I found that calling the static method via object can be very convenient in some use case.
I'm wondering if this is is considered as a bad practice?
or if this feature will be removed in the future version of PHP?
class Foo
{
public static function bar ()
{
echo 'hi';
}
}
class SubFoo extends Foo
{
public static function bar ()
{
echo 'hi subfoo';
}
}
// The normal way to call a static method.
Foo::bar(); // => "hi"
// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"
// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
// The type-hinting `Foo` can be any subclass of `Foo`
// so I have to figure out the class name of `$foo` by calling `get_class`.
$className = get_class($foo);
$className::bar();
// Instead of the above, I can just do `$foo::bar();`
}
callbar(new SubFoo); // => "hi subfoo"
As a general rule, using static methods is bad practice because:
In fact, static methods or static variables are global variables
static code makes can cause many troubles in testing
static code makes high cohesion between parts of code
static code makes hidden dependencies between parts of code
But, there are cases when using static code is justified. For example:
Methods refer to a class and don't refer to objects
Helpers or Util classes which don't have their states
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
inside a template php files, i have hundreds of such code:
echo str_replace('x','y', $this->load1->view('something'));
i have replaced that line everywhere, with code:
echo blabla();
and placed a function in my core library:
function blabla(){
return str_replace('x','y', $GLOBALS['this']->load1->view('something'));
}
but it triggers error: Fatal error...
In PHP, $this refers to the current object. For Example:
class MyClass {
protected $attribute;
public function method() {
$this->attribute;
}
public static function staticMethod() {
//$this is not available here because of the static context!
}
}
$this is used inside the MyClass.
For more details: http://php.net/manual/en/language.oop5.basic.php
Re: your edited question, $this only exists within the class.
You have two options:
function blabla($something){
str_replace('x','y', $something);
}
blablah($this->load1->view('something'));
Or, put function blabla() { inside the class, and drop the global $this line.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to php classes and I was wonder why do I need to declare it to a variable and set it as NEW?
Here is an example :
class myFirstClass {
function Version(){
return 'Version 1';
}
function Info(){
return 'This class is doing nothing';
}
}
$hola = new myFirstClass;
echo $hola->Version();
Why this won't work WITHOUT declare it to a variable and set it to NEW ?
In other words... Without this line :
$hola = new myFirstClass;
I'm so used to functions so it looks weird to me...
This is a basic principle of Object Oriented Programming (OOP). Let's use a library system for example. If you want to get the name of a book, you cannot just say "give me the name of the book", you have to know what book (by id, author, whatever).
In functions, you can write one that looks like this:
function get_book($id){ // code }
In OOP it doesn't really work that way. You have a class book that keeps a name. But that name is only for that given book.
class Book {
var $name;
public __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
In order to call the getName() function we need to have a book. This is what new does.
$book = new Book("my title");
Now if we use the getName() function on $book we'll get the title.
$book->getName(); // returns "my title"
Hope that helps.
You are right! It is not necessary to use the new operator:
class myFirstClass {
static function Version(){// static keyword
return 'Version 1';
}
function Info(){
return 'This class is doing nothing';
}
}
echo myFirstClass::Version();// direct call
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
The Basics
http://php.net/manual/en/language.oop5.basic.php
Classes and Objects
http://php.net/manual/en/language.oop5.php
This line:
$hola = new myFirstClass;
Is saying: create a new object called $hola, then put a new instance of myFirstClass into $hola. Now $hola is literally a object containing a new instance of myFirstClass.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is there any way who let the code below works?
public function my_function(My_Class $arg){ .... }
public class My_Sub_Class extends My_Class { ... }
//NOW
$my_object = new My_Sub_Class();
my_function($my_object);
I've Edited some write errors
public class My_Sub_Class extends My_Class() { }
should be
public class My_Sub_Class extends My_Class { }
Also, I'm not sure what $my_object = new My_Sub_Class(){ .... } is supposed to be. A My_Sub_Class is not a function!
Fixing these errors, adding a definition of My_Class to your testcase, and removing the public prefixes (because your example had no surrounding class definition), I end up with the following, which works just fine:
<?php
class My_Class {}
class My_Sub_Class extends My_Class {}
function my_function(My_Class $arg){ echo "my_function"; }
$my_object = new My_Sub_Class();
my_function($my_object);
?>
Take a look at the extends keyword in the PHP manual.
In fact, take a look at every feature you use in the manual, if you can't get something to "work".
You code works just fine (that is, passing a subclass to function that has a superclass typehint). Here's my code, verified to work on PHP 5.3.3:
<?php
class Foo {}
class Bar extends Foo {}
function quu(Foo $a) { return $a; }
$foo = new Foo();
$bar = new Bar();
var_dump(quu($foo));
var_dump(quu($bar));
Of course, you have a syntax error on your second and third line. But that has nothing to do with your question...
Since the child class extends parent class, it has to have all the properties and methods of the parent class. Because of that, you do not have to fear - your function will receive and work with objects of all the child classes as well.
You have an error in your third line - after initializing an object you do not need curly brackets.