A
A
Alexander Vladimirovich2015-10-22 15:40:47
PHP
Alexander Vladimirovich, 2015-10-22 15:40:47

How to use the current namespace in the successor?

<?php

namespace N1 {
    class C1
    {
    }

    class C2
    {
        public $c1;

        public function __construct()
        {
            $this->c1 = new C1;
        }
    }
}
namespace N2 {
    class C1 extends \N1\C1
    {
    }

    class C2 extends \N1\C2
    {
    }
}
namespace {
    $n1c2 = new \N1\C2;
    var_dump($n1c2);
    $n2c2 = new \N2\C2;
    var_dump($n2c2);
}

result
object(N1\C2)[1]
  public 'c1' => 
    object(N1\C1)[2]

object(N2\C2)[3]
  public 'c1' => 
    object(N1\C1)[4]

wanted to get
object(N1\C2)[1]
  public 'c1' => 
    object(N1\C1)[2]

object(N2\C2)[3]
  public 'c1' => 
    object(N2\C1)[4]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cat Anton, 2015-10-22
@polyanin

ideone.com/wLpMHt

namespace N1 
{
    class C1 { }

    class C2
    {
        public $c1;

        static protected $ns = __NAMESPACE__;

        public function __construct()
        {
            $classname = static::$ns . '\\C1'; 
            $this->c1 = new $classname;
        }
    }
}

namespace N2 
{
    class C1 extends \N1\C1 { }

    class C2 extends \N1\C2
    {
        static protected $ns = __NAMESPACE__;
    }
}

Another option: ideone.com/8XQGrB
namespace N1 
{
    class C1 { }
 
    class C2
    {
        public $c1;
 
        public function __construct()
        {
            $r = new \ReflectionObject($this);
            $classname = $r->getNamespaceName() . '\\C1'; 
            $this->c1 = new $classname;
        }
    }
}
 
namespace N2 
{
    class C1 extends \N1\C1 { }
    class C2 extends \N1\C2 { }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question